我正在尝试在
*.d.ts
打字稿文件中创建更简化的输出,这些文件包含在我的模块代码的捆绑版本中。这些文件是通过涉及 typescript 编译器、babel 和 rollup 的链生成的。我也在使用relay和graphql,但我认为这不会对问题产生太大影响。
举个例子,在
.tsx
源代码中,我有这样的东西:
import { graphql } from 'babel-plugin-relay/macro'
// produces some generated code
graphql`fragment task_model on Task { id message createdAt deadline modifiers { hard medium easy } }`
// There is a generated type for this fragment, but it is a little ugly
import { task_model } from './__generated__/task.graphql'
// We can "correct" the type information and export it with a nicer name
export type Task = Readonly<Omit<task_model & { deadline: string, createdAt: string }, ' $refType'>>
在
.d.ts
输出中,文件显示:
export declare type Task = Readonly<Omit<task_model & {
deadline: string;
createdAt: string;
}, ' $refType'>>;
但是,在功能强大的 IDE 中,我可以看到该类型解析为更合理的
type Task = {
readonly id: string;
readonly message: string;
readonly createdAt: string;
readonly deadline: string;
readonly modifiers: {
readonly hard: number;
readonly medium: number;
readonly easy: number;
};
}
是否有某种选项或某种方式可以输出更清晰的人类可读类型分辨率,而不是描述更正的版本?我认为即使使用该模块的项目未正确配置为使用它,也能够理解类型信息会很好。
我创建了一个工具来做到这一点! ts-simplify 是一个 CLI 工具,可将类型编译为其原语,而不保留任何别名。
现在非常简单,所以我不确定它是否会涵盖所有用例,但很容易尝试!
npx ts-simplify <source> <output>
例如:
type ExampleObj = { deadline: string, createdAt: string, $refType: string };
export type Example = Readonly<Omit<ExampleObj, '$refType'>>;
编译为:
export type Example = { readonly deadline: string, readonly createdAt: string };