简体   繁体   English

Typescript function 扩展接口型

[英]Typescript function extended interface type

I have a function which takes an array of objects which do not have an id property and return all those objects with an id property added to them.我有一个 function ,它接受一个没有 id 属性的对象数组,并返回所有添加了 id 属性的对象。

const pickIdAndDocs = (arr) => {
  return arr.map(doc => ({
    id: 1,
    ...doc
  }))
}

Now, for example if i have this interface现在,例如,如果我有这个界面

interface iUser {
  name: string;
}

and an array containing values of type iUser和一个包含iUser类型值的数组

let users: iUser[] = [ {name: "John"}, {name: "Joe"} ];

How do i specify the return type of the function pickIdAndDocs , such that it returns an array where each item is an extended type of the input type it takes with an added id property如何指定 function pickIdAndDocs的返回类型,以便它返回一个数组,其中每个项目都是输入类型的扩展类型,并添加了 id 属性

function pickIdAndDocs<T>(items : T[] ) : extendedT[];

This function can take an array of any type (will always be objects/key-value pairs), an return all items with an appended id property.这个 function 可以采用任何类型的数组(始终是对象/键值对),返回所有带有附加 id 属性的项目。

Or am i approaching this the wrong way?还是我以错误的方式接近这个? Thanks:)谢谢:)

Essentially we want to build up new type by combining two types.本质上,我们希望通过组合两种类型来构建新类型。 One with {id: number} and another is whatever passed to the function.一个带有{id: number}另一个是传递给 function 的任何内容。 This exactly what intersection type does.这正是intersection type的作用。 Assuming my interpretation of your problem is correct, I think this is what you want:假设我对您的问题的解释是正确的,我认为这就是您想要的:

interface User {
  name: string;
}

type WithId<T> = T & { id: number };

const pickIdAndDocs = <T,>(arr: T[]): WithId<T>[] => {
  return arr.map((doc) => ({
    id: 1,
    ...doc,
  }));
};

let users: User[] = [{ name: "John" }, { name: "Joe" }];

const usersWithId = pickIdAndDocs(users);

// No warning!
usersWithId[0].id;
usersWithId[0].name;

// Warning: Property 'age' does not exist on type 'WithId<User>'.
usersWithId[0].age;

Here is the TS Playground link: https://tsplay.dev/ND5B4m这是 TS Playground 链接: https://tsplay.dev/ND5B4m

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

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