Typescript dynamically create types based on object

Mat*_*ahl 5 typescript

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)

bel*_*a53 5

最新的 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可能会在最终版本中发生变化。