1

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
}

1 Answer 1

2

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: ''
}
Sign up to request clarification or add additional context in comments.

4 Comments

A little shorthand you could use -> type Obj = Record<typeof keys[number], any>;
@Keith I know, I just wanted to explain it step by step so it's easier to understand to the person that has asked the question. Thanks!
Yes, that's fine. But for anybody coming across this post, it might help to also show the Record type, as it's a tad easier to reason with. Showing how to do it manually is certainly not a bad thing to show too :)
the as const syntax is really helpful, thanks, nice guys!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.