【问题标题】:Typescript interfaces: Any way to describe "<Property> of <Interface>"Typescript 接口:描述“<Interface> 的<Property>”的任何方式
【发布时间】:2018-08-19 16:58:49
【问题描述】:

快速示例:

public processList<T extends {}>(list: T[], targetProperty: ???) {
    // do something with target property...
}

我想要一个描述T接口的类型。因此,如果T 的类型为{ a: string, b: boolean },那么我希望targetProperty 接受ab

我知道我可以通过使用包含目标属性名称的字符串来解决这个问题。含义类似于targetProperty = 'myProperty' 然后item[targetProperty] = ... 但我认为这可能会在未来中断(例如当 T 的接口发生变化时)。

有没有办法做到这一点?或者有其他建议吗?

谢谢!

【问题讨论】:

  • keyof T......

标签: typescript generics interface


【解决方案1】:

不幸的是,没有办法将变量类型声明为 SomeInterface.Property,因为 Typescript 既不是基于其自身的优点,也不是基于 Javascript 运行时不是一种反射语言。没有办法以如此简单的方式建立运行时检查。

作为静态检查,有一个索引类型查询keyof

interface Person {
    name: string;
    age: number;
    location: string;
}

type K1 = keyof Person; // "name" | "age" | "location"
type K2 = keyof Person[];  // "length" | "push" | "pop" | "concat" | ... 

这个查询产生的结果是一个类型本身,所以你声明额外的泛型约束为

function getProperty<T, K extends keyof T>(obj: T, key: K) {
     return obj[key];  // Inferred type is T[K]
}

来源https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-1.html

【讨论】:

    猜你喜欢
    • 2016-03-24
    • 2017-08-08
    • 2020-09-03
    • 2019-04-06
    • 2016-08-09
    • 1970-01-01
    • 2019-02-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多