简体   繁体   English

TypeScript 不推断传递的泛型类型

[英]TypeScript doesn't infer the type of passed generic

I'm trying to define flexible types for my api responses, but can't figure out how to approach type conversion using TypeScript 4.5.4.我正在尝试为我的 api 响应定义灵活的类型,但无法弄清楚如何使用 TypeScript 4.5.4 进行类型转换。 I'd like to parse the response and get the type that I'll be using later in the code, the response type is just for proper typing before parse.我想解析响应并获取稍后将在代码中使用的类型,响应类型仅用于在解析之前正确键入。

TS Playground (EDIT: fixed id) TS 游乐场(编辑:固定 ID)

// this and ReviewResponse are specific to reviews
export type Review = {
  id: number;
  name: string;
  rating: number;
  review: string;
};

export type ReviewResponse = ResponseType<Review>;

// this is a general type placed elsewhere
export type ResponseType<Item> = {
  id: number;
  attributes: {
    [key: string]: Item
  }
}

// parser function to run after fetching the data
function parseResponse(data: ReviewResponse[]): Review[] {
  return data.map((item) => {
    return {
      id: item.id,
      ...item.attributes,
    };
  });
}

Function parseResponse has an error visible below. Function parseResponse有一个错误可见如下。 Why TS doesn't understand that Item is of type Review, what am I missing?:为什么 TS 不明白 Item 是 Review 类型,我错过了什么?:

Type '{ id: number; }[]' is not assignable to type 'Review[]'.
  Type '{ id: number; }' is missing the following properties from type 'Review': name, rating, review (2322)

If attributes contains an object with the other attributes of the object it's type should be Item , or more specifically Omit<Item, 'id'> .如果attributes包含 object 和 object 的其他属性,则它的类型应该是Item ,或者更具体地说是Omit<Item, 'id'>

export type ResponseType<Item> = {
  id: string;
  attributes: Omit<Item, 'id'>
}

// parser function to run after fetching the data
function parseResponse(data: ReviewResponse[]): Review[] {
  return data.map((item) => {
    return {
      id: item.id,
      ...item.attributes,
    };
  });
}

Playground Link 游乐场链接

[key: string]: Item means that attributes could have multiple Item properties under different keys. [key: string]: Item表示属性在不同的key下可以有多个Item属性。 So it could be something like { "A": { /*attributes of Review*/ }, "B": { /*attributes of Review*/ } }所以它可能类似于{ "A": { /*attributes of Review*/ }, "B": { /*attributes of Review*/ } }

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

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