Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Type conversion: Convert type of Object with uniformly typed fields to Array type in Typescript

Say I want to convert an the type of an object whose fields are uniformly typed, as string for example:

// imported from 3rd-party
const event = {
 RAIN: "RAIN",
 SUN: "SUN",
 CLOUDY: "CLOUDY",
}

type EventType = typeof event

How would I go about converting that type to the Array of strings type ?

EDIT : I shoul have added that I don’t control the eventtype, it’s from a third party

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

const event1 = {
    RAIN: "RAIN",
    SUN: "SUN",
    CLOUDY: "CLOUDY",
}
type EventType = typeof event1
// type EventType = {
//     RAIN: string;
//     SUN: string;
//     CLOUDY: string;
// }
const keys1 = Object.keys(event1) as (keyof typeof event1)[]
// const keys1: ("RAIN" | "SUN" | "CLOUDY")[]

const event2 = {
    RAIN: "RAIN",
    SUN: "SUN",
    CLOUDY: "CLOUDY",
} as const
type EventType2 = typeof event2
// type EventType2 = {
//     readonly RAIN: "RAIN";
//     readonly SUN: "SUN";
//     readonly CLOUDY: "CLOUDY";
// }
type ValuesOf<T> = T[keyof T];
const values2 = Object.values(event3) as ValuesOf<typeof event2>[];
// const values2: ("RAIN" | "SUN" | "CLOUDY")[]

enum event3 {    
    RAIN = "RAIN",
    SUN = "SUN",
    CLOUDY = "CLOUDY",
}
// const event3 = {
//     RAIN: "RAIN",
//     SUN: "SUN",
//     CLOUDY: "CLOUDY",
// }
type EventType3 = event3
// ~= type EventType3 = "RAIN" | "SUN" | "CLOUDY"
// ~= type EventType3 = event3.RAIN | event3.SUN | event3.CLOUDY
const values3 = Object.values(event3) as event3[]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading