可以通过简单地分析对象属性(例如像这样的对象)来动态生成类型注释:
cons myObj = {
start() { /*...*/ },
}
我要生成/返回以下类型:
type Props = {
start: () => void;
isScreenStart: () => boolean;
isStartAllowed: () => boolean;
}
给出advance
之类的属性,它应生成以下类型
advance: () => void;
isScreenAdvance: () => boolean;
isAdvanceAllowed: () => boolean;
答案 0 :(得分:1)
latest TS version(4.1)可以实现:
type Generate<T> = {
[K in keyof T & string as T[K] extends Function ?
`isScreen${capitalize K}` | `is${capitalize K}Allowed` :
never]: () => boolean
} & T
type Generated = Generate<typeof myObj>
// { isScreenStart: () => boolean; isStartAllowed: () => boolean; } & { start(): void; }
您可以查看this sample code。请注意,最终版本的编译器关键字capitalize
为subject to change。