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
>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[]