1 回答
TA贡献1777条经验 获得超10个赞
我能找到的最干净的解决方案如下:
interface UserProps {
name?: string;
age?: number;
}
export class User {
constructor(private data: UserProps) {}
// Add generic magic here
get<K extends keyof UserProps>(propName: K): UserProps[K] {
return this.data[propName];
}
set(update: UserProps): void {
Object.assign(this.data, update);
}
}
或者,您可以添加任意键索引以及更新 get 语句的类型。
interface UserProps {
name?: string;
age?: number;
// this next line is important
[key: string]: string | number | undefined;
}
export class User {
constructor(private data: UserProps) {}
// number|string changed to number|string|undefined
get(propName: string): number | string | undefined {
return this.data[propName];
}
set(update: UserProps): void {
Object.assign(this.data, update);
}
}
添加回答
举报