Search code examples
typescript

Declare a type that is a union of the types of the properties of an interface


I have an interface:

{
   a: string,
   b: number
}

I want to make a type that can, based on the above interface, be either a string or a number. So, a type that 'does the same thing' as the following:

type MyType = string | number

But created based from the interface, like type MyType = {any type from the properties of the interface}


Solution

  • You can use it like this:

    interface MyInterface {
       a: string;
       b: number;
    }
    
    type MyType = MyInterface[keyof MyInterface];
    
    const test1: MyType = "abc";
    const test2: MyType = 55;