请问 getIncludeAttrs 函数的的 type 该怎么写可以得到期望的类型?
let obj = getIncludeAttrs(['name', 'age'], { name: '小明', age: 10, address: "xxx" })
// 期望返回的 obj 类型声明为: {name:string, age:number }
请问 getIncludeAttrs 函数的的 type 该怎么写可以得到期望的类型?
let obj = getIncludeAttrs(['name', 'age'], { name: '小明', age: 10, address: "xxx" })
// 期望返回的 obj 类型声明为: {name:string, age:number }
interface PersonInfo {
name: string;
age: number;
address: string;
}
function getIncludeAttrs(keys: (keyof PersonInfo)[], personInfo: PersonInfo): {
[p in keyof PersonInfo]?: PersonInfo[p]
} {
return { name: '小明', age: 10}
}
您可以定义一个类型,用于描述返回的对象的形状,然后将这个类型作为函数的返回值类型。例如:
type ReturnType = {
name: string,
age: number
}
function getIncludeAttrs(keys: string[], obj: any): ReturnType {
//
}
现在,当调用 getIncludeAttrs 函数时,它的返回值类型会被推断为 ReturnType,即 {name:string, age:number}。
同时,您可以使用 TypeScript 的类型断言来确保 getIncludeAttrs 函数返回的对象具有期望的形状。例如:
let obj = getIncludeAttrs(['name', 'age'], { name: '小明', age: 10, address: "xxx" }) as ReturnType;
在这里,我们将 obj 的类型断言为 ReturnType,告诉编译器 obj 的形状应该为 {name:string, age:number}。
希望这能够帮助您。