【问题标题】:How to create interface based on properties of the object?如何根据对象的属性创建接口?
【发布时间】:2018-10-17 01:52:05
【问题描述】:

我正在使用最新的 TypeScript 和 Angular,并且我有一个对象:

const obj: ObjInterface = {
 prop1: 1,
 prop2: 2,
 prop3: '3'
}

我也有基于该对象的接口:

interface ObjInterface {
  prop1: number;
  prop2: number;
  prop3: string;
}

是否可以创建仅由obj 的属性组成的数组接口?

const array: SomeInterface = ['prop1', 'prop2', 'prop3']; // OK
const array: SomeInterface = ['prop1', 'prop2', 'prop4']; // error

【问题讨论】:

  • 运行时接口不存在

标签: javascript angular typescript interface


【解决方案1】:

您可以使用keyof 运算符创建一个类型的键数组

interface ObjInterface {
    prop1: number;
    prop2: number;
    prop3: string;
}
const array: Array<keyof ObjInterface> = ['prop1', 'prop2', 'prop3']; // OK
const array2: Array<keyof ObjInterface> = ['prop1', 'prop2', 'prop4']; // error

注意这将是一个编译时错误,如果您在类型系统之外冒险或使用类型断言,则在运行时您可以在数组中包含不同的字符串。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-30
    • 2021-11-25
    • 1970-01-01
    • 2012-10-20
    • 2019-03-09
    相关资源
    最近更新 更多