Javascript 如何在TypeScript中为模板定义类型?

Javascript 如何在TypeScript中为模板定义类型?,javascript,typescript,types,typescript-generics,Javascript,Typescript,Types,Typescript Generics,我将定义一个类型,我可以在其中存储来自具有类似响应的各种API的响应 反应看起来像 type TResponse<E> = { Code: number; Message: string; Result: { [i: string]: Array<E>; Count: number; }; Status: string; } 类型响应={ 代码:编号; 消息:字符串; 结果:{ [i:string]:数组; 计数:

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

反应看起来像

type TResponse<E> = {
   Code: number;
   Message: string;
   Result: {
      [i: string]:  Array<E>;
      Count: number;
   };
   Status: string;
}
类型响应={
代码:编号;
消息:字符串;
结果:{
[i:string]:数组;
计数:数字;
};
状态:字符串;
}
[i:string]
可以是除
计数
以外的任何内容,具体取决于API设计,例如,
日志
等。
现在这给了我一个错误,因为
Count
属性与
[i:string]
冲突


另外,我使用的是typescript版本^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[]
此外,尝试创建这样的对象需要类型断言:

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>
const response2:t响应={
代码:0,
消息:“”,
//类型“{Count:number;}”不可分配给类型。。。
结果:{
计数:1
},
状态:“”
}
常数响应3={
代码:0,
消息:“”,
结果:{
计数:1
},
状态:“”
}作为响应

我可以通过使用
{[I:string]:数组| number;Count:number;}
用于
结果
但不确定这是否是最佳解决方案我认为TS编译器不会让您表达您想要的内容,因为它不能与任何对象属性共存。也许将
计数
作为
结果
的同级存储在外部?(即,
ResultCount
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>