Reputation: 4211
I have a question for typescript. I want to create somemething like union from a object values. How I can achieve this? eg:
const x = {
x: 1,
y: 2,
z: 'a string',
k: document.createElement('div')
}
const y = (y: the value which exist of x ): boolean => {
return true
}
Something like:
type ValueOf<T> = T[keyof T];
but for objects. Any hints are welcome.
Upvotes: 3
Views: 7401
Reputation: 250376
To get a union of the values in the type of a variable you can use ValueOf<typeof x>
. For your example that type would be string | number | HTMLDivElement
const x = {
x: 1,
y: 2,
z: 'a string',
k: document.createElement('div')
}
type ValueOf<T> = T[keyof T];
const y = (P: ValueOf<typeof x>): boolean => { // p: string | number | HTMLDivElement
return true
}
From the comments you want the literal types (1 | 2 | "a string"
) not the base types. For this to work, you need to change the type pf x
to include the literal types. The simplest way to do this is in 3.4 to add a const
assertion:
const x = {
x: 1,
y: 2,
z: 'a string',
k: document.createElement('div')
} as const
type ValueOf<T> = T[keyof T];
const y = (p: ValueOf<typeof x>): boolean => { // p: 1 | 2 | "a string" | HTMLDivElement
return true
}
Upvotes: 13
Reputation: 1121
I think this is what you need:
export const xx = {
x: 1,
y: 2,
z: 'a string',
k: document.createElement('div')
};
type ValueOf<T> = T[keyof T];
type XValues = ValueOf<typeof xx>;
Upvotes: 4