It's possible to dynamically generate type annotation by simply analyze an object properties, example an object like:
cons myObj = {
start() { /*...*/ },
}
Run Code Online (Sandbox Code Playgroud)
I want to generate/return the follow type:
type Props = {
start: () => void;
isScreenStart: () => boolean;
isStartAllowed: () => boolean;
}
Run Code Online (Sandbox Code Playgroud)
Given a property like advance, it should generate the follow types
advance: () => void;
isScreenAdvance: () => boolean;
isAdvanceAllowed: () => boolean;
Run Code Online (Sandbox Code Playgroud)
最新的 TS 版本(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; }
Run Code Online (Sandbox Code Playgroud)
你可以看一下这个示例代码。请注意,编译器关键字 capitalize可能会在最终版本中发生变化。
| 归档时间: |
|
| 查看次数: |
3727 次 |
| 最近记录: |