Home > Back-end >  Get union of object types in Typescript?
Get union of object types in Typescript?

Time:12-18

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) => {
...
}

CodePudding user response:

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

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

}

enter image description here

  • Related