Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to reference derived types in typescript?

Having object A:

interface A {
   boolProp: boolean,
   stringProp: string,
   numberProp: number,
   ...other props/methods...
}

Then I want to have objects, which holds one of the A properties and defines default value for it, other properties are irrelevant to this issue.

interface B {
    prop: keyof A,
    default: typeof keyof A,
   ...other props/methods...
}

I want to get TS error when I try to set default value of different type

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

const b: B = {
  prop: 'stringProp',
  default: true, // expecting to get TS error as true cannot be assigned to string
};

Thank you in advance for any help 🙏

>Solution :

You essentially want a union type which holds all valid prop/default combinations. This can be programmatically generated with a mapped type which maps over the keys of A and is indexed with keyof A.

type B = {
    [K in keyof A]: {
        prop: K
        default: A[K]
    }
}[keyof A] & {
    /* ... put all the other props of B here */ 
}

Playground

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading