【问题标题】:How to define a type for a template in TypeScript?如何在 TypeScript 中为模板定义类型?
【发布时间】:2020-12-15 21:21:03
【问题描述】:

我将定义一个类型,我可以在其中存储来自具有相似响应的各种 API 的响应。

响应看起来像

type TResponse<E> = {
   Code: number;
   Message: string;
   Result: {
      [i: string]:  Array<E>;
      Count: number;
   };
   Status: string;
}

[i: string] 可以是除Count 之外的任何内容,具体取决于 API 设计,例如,RowsValuesLogs 等...
现在这给了我一个错误,因为 Count 属性与 [i: string] 冲突。

附:我正在使用打字稿版本 ^3.9.7

【问题讨论】:

  • 我可以通过使用{ [i: string]: Array&lt;E&gt; | number; Count: number; };Result 解决此问题,但不确定这是否是最佳解决方案
  • 我认为 TS 编译器不会让你表达你想要的,因为index type definitions 不能与任何对象属性共存。也许将Count 存储为Result 的兄弟姐妹? (即ResultCount

标签: javascript typescript types typescript-generics


【解决方案1】:

你可以使用交集类型:

type TResponse<E> = {
   Code: number;
   Message: string;
   Result: {
      [i: string]: Array<E>;
    } & {
      Count: number;
   };
   Status: string;
}

declare const response: TResponse<string>;
response.Result.Count; // number
response.Result.abc; // string[]

请注意,这有点不安全,这就是 TS 要求所有属性都可分配给其索引签名的原因:

declare const key: string;
response.Result[key]; // string[] even though key could be Count

此外,尝试创建这样的对象需要类型断言:

const response2: TResponse<string> = {
   Code: 0,
   Message: '',
   // Type '{ Count: number; }' is not assignable to type ...
   Result: {
      Count: 1
   },
   Status: ''
}

const response3 = {
   Code: 0,
   Message: '',
   Result: {
      Count: 1
   },
   Status: ''
} as TResponse<string>

Playground link

【讨论】:

    猜你喜欢
    • 2018-03-19
    • 1970-01-01
    • 2020-01-23
    • 2018-02-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-20
    相关资源
    最近更新 更多