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:
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.)
You have two solutions. Either
export interface Data {
foo: string;
bar: number;
}
type propName = 'bar';
type propType = Data[propName]; //number
or
export interface Data {
foo: string;
bar: number;
}
const propName = 'bar'; //or let propName: 'bar' = 'bar' (both are type literals)
type propType = Data[typeof propName]; //number (typeof propName is 'bar')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With