6

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 Answer 1

6

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you very much!
And capitalize did change. You can correct the above code by replacing capitalize K with Capitalize<K>.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.