Is there a way to "extract" the type of TypeScript interface property?
To expand on the accepted answer, you can also assign the type using the type
keyword and use it in other places.
// Some obscure library
interface A {
prop: {
name: string;
age: number;
}
}
// Your helper type
type A_Prop = A['prop']
// Usage
const myThing: A_prop = { name: 'June', age: 29 };
It wasn't possible before but luckily it is now, since TypeScript version 2.1. It has been released on the 7th of December 2016 and it introduces indexed access types also called lookup types.
The syntax looks exactly like element access but written in place of types. So in your case:
interface I1 {
x: any;
}
interface I2 {
y: {
a: I1,
b: I1,
c: I1
}
z: any
}
let myVar: I2['y']; // indexed access type
Now myVar
has type of I2.y
.
Check it out in TypeScript Playground.
Just an example of extracting a literal type from the union object type:
type Config = {
key: "start_time",
value: number,
} | {
key: "currency",
value: string,
}
export type ConfigKey = Config["key"];
// "start_time"|"currency"
keyof Colors
will return a list of all keys "white" | "black"
. When this list of keys gets passed to the Colors interface, the type will be all the values of the given keys, "#fff" | #000
.
interface Colors {
white: "#fff"
black: "#000"
}
type ColorValues = Colors[keyof Colors]
// ColorValues = "#fff" | "#000"