Is it possible to get the type of an object property using a variable? I.e. using the string x, I would like to get string type and using the string y I want to get number type.
type Obj = Readonly<{
x: string,
y: number
}>
const obj = {
x: 'abc',
y: 123
}
type TypeOfX = Obj['x']; // this works fine and returns string
type TypeOfY = Obj['y']; // this works fine and returns number
type Property = keyof Obj;
const property: Property = 'x';
// error here
type TypeOfObjProperty = Obj[property];
The errors are:
Type 'any' cannot be used as an index type.(2538)
'property' refers to a value, but is being used as a type here. Did you mean 'typeof property'?(2749)
Exported type alias 'TypeOfObjProperty' has or is using private name 'property'.(4081)
property) to define a compile-time construct (a type). You could doconst property = "x";and thenObj[typeof property], becausetypeof propertywould be the string literal type"x". But you can't do it with the value of the variable, just its type.propertyis of typekeyof ObjandObjis readonly, isn't it known at compile time that the value can only bexory?type TypeOfObjProperty = Obj[typeof property];it will correctly infer the type asstringornumberdepending on thepropertyvariable. Is that what you want?typeof propertywith this specific example, it'll work (because TypeScript's flow analysis tells it thatpropertyis of type"x"). If TS couldn't determine that from flow analysis, the type you'd get would bestring | numberbecause the type ofpropertyis"x" | "y"(playground). ButObj[property]is usingpropertyas a value, not as a type.if (key === 'a' || key === 'b') {, rather than working out the type of the key which typescript can't know because it's not there at runtime.