Typescript dynamically create types based on object

Viewed 1884

It's possible to dynamically generate type annotation by simply analyze an object properties, example an object like:

cons myObj = {
        start() { /*...*/ },
}

I want to generate/return the follow type:

type Props = {
  start: () => void;
  isScreenStart: () => boolean;
  isStartAllowed: () => boolean;
}

Given a property like advance, it should generate the follow types

advance: () => void;
isScreenAdvance: () => boolean;
isAdvanceAllowed: () => boolean;
1 Answers

That will be possible with the 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; }

You can take a look at this sample code. Be aware, that the compiler keyword capitalize is subject to change for the final release.

Related