Within my Typescript interface, there are numerous properties. In the absence of any instance of this interface, I aim to identify the type of a specific property.
export interface Data {
foo: string;
bar: number;
.
.
.
}
One way to achieve this is by using an index signature with a fixed string on Data
.
type propType = Data['foo']; // propType = 'string'
Unfortunately, attempting to use a variable in place of the fixed string does not work.
const propName = 'foo';
type propType = Data[propName]; // Errors
The errors encountered are:
- 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)
These error messages may seem confusing since propName
is clearly a string
and not of type any
, and it is not being utilized as a type in this context.
Update:
Upon further reflection, it becomes evident that what I was attempting to do is unattainable. After much effort, I have come to terms with the fact that interfaces without instances will never possess property or property-type information at runtime.
While the method utilizing type
will function during compilation, it is limited to compile-time only. The correct syntax for this approach has been acknowledged in the accepted answer.
(I still find the error messages mentioned in my query to be peculiar.)