如何在 TypeScript 中为模板定义类型? [英] How to define a type for a template in TypeScript?

查看:43
本文介绍了如何在 TypeScript 中为模板定义类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm going to define a type where I can store the response from various API that has similar responses.

响应看起来像

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

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

[i: string] can be anything except for Count depending on the API design, for example, Rows, Values, Logs, etc...
This for now gives me an error, because of the Count property conflicts with [i: string].

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

P.S. I'm using the typescript version ^3.9.7

推荐答案

您可以使用交集类型:

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 要求所有属性都可以分配给其索引签名的原因:

Note that this is slightly unsafe, which is why TS requires that all properties are assignable to its index signature:

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

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

Also, trying to create objects like this requires a type assertion:

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>

游乐场链接

这篇关于如何在 TypeScript 中为模板定义类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆