简体   繁体   English

动态键值键入 Typescript

[英]Dynamic key Value Typing Typescript

I need a little help here.我需要一点帮助。

My API response is as below:我的 API 响应如下:

Week At A Glance: { objA: [{}], objB: [{}] },
records: { Employee Records: [{}], Email Records: [{}], message: "" },
history: { [{}] }

When i am trying to create a model for it as below, i am not able to proceed.当我尝试如下为其创建 model 时,我无法继续。 I created as below我创建如下

interface DesiredResponse {
    [key: string] : {
        objA: ObjA[],
        objB: ObjB[]
    },
    records: Records[],
    history: History[]
}

interface Records {
    [key: string]: EmpRecords | EmailRecords;
    message: string
}

Typescript error: Property 'records' of type 'Records[]' is not assignable to string index type '{ objA: BbjA[]; Typescript 错误: 'Records[]' 类型的属性 'records' 不可分配给字符串索引类型 '{ objA: BbjA[]; objB: ObjB[] }' objB: objB[] }'

Property 'message' of type 'string' is not assignable to string index type 'EmpRecords | 'string' 类型的属性 'message' 不可分配给字符串索引类型 'EmpRecords | EmailRecords'电子邮件记录'

How can i efficiently type it so that i get auto suggestion while accessing this model.如何有效地键入它,以便在访问此 model 时获得自动建议。

EDIT:编辑:

This is actually caused by a single issue in your code where you've defined your interface to use a list version of the Records interface for your records property as compared to what your API response is actually returning (not an array - an object):这实际上是由您的代码中的一个问题引起的,您在其中定义了接口以使用Records接口的列表版本作为您的records属性,而不是您的 API 响应实际返回的内容(不是数组 - 对象):

interface DesiredResponse {
  // ...
  records: Records; // Originally Records[]
}

Original answer:原答案:

This is because defining separate properties in a TypeScript interface usually requires you to use semicolons instead of commas, unlike that of JSON where you could do the opposite (aka use commas instead of semicolons):这是因为在 TypeScript 接口中定义单独的属性通常需要您使用分号而不是逗号,这与 JSON 不同,您可以执行相反的操作(也就是使用逗号而不是分号):

export interface MyInterface {
  property1: string;
  property2: boolean;
  // etc
}

vs:与:

export interface MyInterface {
  property1: string,
  property2: boolean // Would not compile
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM