Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get Typescript interface property type, given property name only

Tags:

typescript

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.)

like image 233
katie Avatar asked Nov 01 '19 21:11

katie


1 Answers

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')
like image 124
jperl Avatar answered Oct 16 '22 08:10

jperl