typescript - 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 属性的项目。
还是我以错误的方式接近这个?谢谢 :)
解决方案
本质上,我们希望通过组合两种类型来构建新类型。一个与{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
推荐阅读
- email - 使用 zoho 的 Rocket Chat smtp 传出电子邮件设置不起作用
- python - 如何使用 WTF 表单快速表单上传图像
- r - 无法在绘图小提琴图中抑制 x 轴标签
- javascript - 异常的浏览器错误和有关 javaScript 计算总和程序的建议
- javascript - 当我从车把返回一个值时,我作为一个对象获得了价值。如何获得内部价值
- mysql - 3 mysql 表连接但没有得到我想要的预期结果
- javascript - 从 youtube 或其他网站上传 vimeo 上的视频
- python - 我可以使用 tf.sparse_split 在可变数量的部分中动态拆分张量吗?
- .net-core - MVC Core 2 外部用户和访问令牌
- maven - 由于软件包不存在,无法运行 maven install 出现编译时错误,任何人都可以帮助我