johnbumble
johnbumble

Reputation: 700

Get union of object types in Typescript?

Is it possible to get only the types of an object in typescript with a certain keyword. I don't think keyof is what I want, unless I am misunderstanding what it does.

For example instead of saying something: string | number | DOB I want to use some Typescript construct to get the types that something can be from obj:

const obj = {
 name: string;
 age: number;
 birthdate: DOB;
}

const printObjectField(something: string | number | DOB) => {
...
}

Upvotes: 0

Views: 22

Answers (1)

Acid Coder
Acid Coder

Reputation: 2747

const obj = {
 name: "abc",
 age: 123,
 birthdate: new Date(),
}

const abc=(something: typeof obj[keyof typeof obj]) => {

}

enter image description here

Upvotes: 1

Related Questions