【问题标题】:Typescript - How to type unknown properties of an object? [duplicate]Typescript - 如何键入对象的未知属性? [复制]
【发布时间】:2020-11-08 08:39:48
【问题描述】:

假设有一个变量resp接收来自服务器的响应:

const resp = await ServerResponse();

我确定响应具有ready: boolean 属性:

console.log(resp);
/**
 * {
 *   "ready": true
 * }
 */

但是可能有可选参数,具体的类型我不知道

console.log(resp);
/**
 * {
 *   "ready": true,
 *   "_startAt": 1234567890
 * }
 */

我应该如何输入这个?

interface R {
  ready: boolean;
  //...args: any; //something like this
}
const resp: R = await ServerResponse();

或者还有另一种方式,不给resp变量赋值any,这样访问未知属性的时候,TS不发誓?

【问题讨论】:

    标签: typescript


    【解决方案1】:

    好吧,我们可以将索引属性的值设为松散类型any

    interface R{
      name: string;
      age: number;
      [prop: string]: any; // but this defeats the purpose of providing good typing.
    }
    

    另一种方法是将 additionalProperties 设为字典

    interface R {
      name: string;
      age: number;
      additionalProperties: { [prop: string]: string}; 
    }
    

    您也可以在此处查看更多信息 Typescript interface for objects with some known and some unknown property names

    【讨论】:

    猜你喜欢
    • 2020-06-17
    • 2021-01-11
    • 1970-01-01
    • 2021-02-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-04
    • 1970-01-01
    相关资源
    最近更新 更多