简体   繁体   English

获取 Typescript 接口属性类型,仅给定属性名称

[英]Get Typescript interface property type, given property name only

I have a Typescript interface with many properties.我有一个具有许多属性的 Typescript 接口。 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.这可以在具有非变量字符串的Data上使用索引签名。

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)类型“任何”不能用作索引类型.ts(2538)
  • 'propName' refers to a value, but is being used as a type here.ts(2749) 'propName' 指的是一个值,但在此处用作类型.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."这些错误都没有意义,因为propName绝对是string而不是any ,并且它不是“在这里被用作类型”。

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.这种使用type的方法将起作用,但仅在编译时起作用。 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')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM