Home > Blockchain >  Can I create a new type based on the elements of an array in typescript?
Can I create a new type based on the elements of an array in typescript?

Time:10-19

If now I have an array keys:

const keys = ['firstname', 'lastname']

Can I map all the items as the key of NewType like this below?

type NewType = {
  firstname: any
  lastname: any
}

CodePudding user response:

First you need to use as const syntax to tell TS your array values won't change:

const keys = ['firstname', 'lastname'] as const;

Then you can create a union type from the array values:

type Union = typeof keys[number]; // type Union = "firstname" | "lastname"

And then use mapped types to create the NewType like so:

type Obj = {
    [k in Union]: any;
}

// type Obj = {
//     firstname: any;
//     lastname: any;
// }

const obj: Obj = {
    firstname: '',
    lastname: ''
}
  • Related