Typescript 函数扩展接口类型
Typescript function extended interface type
我有一个函数,它接受一个没有 id 属性 的对象数组,return 所有那些添加了 id 属性 的对象。
const pickIdAndDocs = (arr) => {
return arr.map(doc => ({
id: 1,
...doc
}))
}
现在,例如,如果我有这个界面
interface iUser {
name: string;
}
和一个包含类型 iUser
值的数组
let users: iUser[] = [ {name: "John"}, {name: "Joe"} ];
我如何指定函数 pickIdAndDocs 的 return 类型,以便它 return 是一个数组,其中每个项目都是添加了 id 属性
的输入类型
function pickIdAndDocs<T>(items : T[] ) : extendedT[];
这个函数可以接受任何类型的数组(总是 objects/key-value 对),return 所有带有附加 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 游乐场 link:https://tsplay.dev/ND5B4m
我有一个函数,它接受一个没有 id 属性 的对象数组,return 所有那些添加了 id 属性 的对象。
const pickIdAndDocs = (arr) => {
return arr.map(doc => ({
id: 1,
...doc
}))
}
现在,例如,如果我有这个界面
interface iUser {
name: string;
}
和一个包含类型 iUser
值的数组let users: iUser[] = [ {name: "John"}, {name: "Joe"} ];
我如何指定函数 pickIdAndDocs 的 return 类型,以便它 return 是一个数组,其中每个项目都是添加了 id 属性
的输入类型function pickIdAndDocs<T>(items : T[] ) : extendedT[];
这个函数可以接受任何类型的数组(总是 objects/key-value 对),return 所有带有附加 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 游乐场 link:https://tsplay.dev/ND5B4m