首页 > 解决方案 > Typescript 函数扩展接口类型

问题描述

我有一个函数,它接受一个没有 id 属性的对象数组,并返回所有添加了 id 属性的对象。

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

现在,例如,如果我有这个界面

interface iUser {
  name: string;
}

和一个包含iUser类型值的数组

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

我如何指定函数pickIdAndDocs的返回类型,以便它返回一个数组,其中每个项目都是它采用的输入类型的扩展类型,并添加了 id 属性

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

此函数可以采用任何类型的数组(始终是对象/键值对),并返回所有带有附加 id 属性的项目。

还是我以错误的方式接近这个?谢谢 :)

标签: typescriptgenericstypescript-genericstypescript-types

解决方案


本质上,我们希望通过组合两种类型来构建新类型。一个与{id: number}另一个是传递给函数的任何东西。这正是做什么intersection type。假设我对您的问题的解释是正确的,我认为这就是您想要的:

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;

这是 TS Playground 链接:https ://tsplay.dev/ND5B4m


推荐阅读