I have a Typescript interface with many properties. Without any instance of this interface, I need to determine the type of a given property.
export interface Data {
foo: string;
bar: number;
.
.
.
}
This is possible using index signature on Data with a non-variable string.
type propType = Data['foo']; // propType = 'string'
However, it does not work using a variable.
const propName = 'foo';
type propType = Data[propName]; // Errors
Errors:
- Type 'any' cannot be used as an index type.ts(2538)
- 'propName' refers to a value, but is being used as a type here.ts(2749)
Neither of these errors make sense, because propName is definitely a string not any, and it is not "being used as a type here."
Update
As it might be obvious, I was trying to do something impossible. After much fighting, I've finally accepted that uninstantiated interfaces do not and will not ever have property or property-type information at run-time.
This method using type will work, but only at compile-time. I approved the answer with the correct syntax.
(Still think the error messages in my question are weird though.)
Data[typeof propName]?type propType = Data['foo']is for compile time stuff - at run time I'm pretty sure your only option is to use typeof on an initialized object.keyofbut unfortunately that yields the exact same errors.