猿问

TypeScript 中类的动态 getter 和设置

我在课堂上使用动态 getter 检索数据时遇到问题。


这是我得到的错误:


元素隐式具有“任何”类型,因为“字符串”类型的表达式不能用于索引类型“UserProps”。在类型“UserProps”.ts(7053) 上未找到具有“字符串”类型参数的索引签名


这是代码


interface UserProps {

  name?: string;

  age?: number;

}


export class User {

  constructor(private data: UserProps) {}


  get(propName: string): number | string {

    return this.data[propName];

  }


  set(update: UserProps): void {

    Object.assign(this.data, update);

  }

}


偶然的你
浏览 186回答 1
1回答

不负相思意

我能找到的最干净的解决方案如下:interface UserProps {&nbsp; &nbsp; name?: string;&nbsp; &nbsp; age?: number;}export class User {&nbsp; &nbsp; constructor(private data: UserProps) {}&nbsp; &nbsp; // Add generic magic here&nbsp; &nbsp; get<K extends keyof UserProps>(propName: K): UserProps[K] {&nbsp; &nbsp; &nbsp; &nbsp; return this.data[propName];&nbsp; &nbsp; }&nbsp; &nbsp; set(update: UserProps): void {&nbsp; &nbsp; &nbsp; &nbsp; Object.assign(this.data, update);&nbsp; &nbsp; }}或者,您可以添加任意键索引以及更新 get 语句的类型。interface UserProps {&nbsp; &nbsp; name?: string;&nbsp; &nbsp; age?: number;&nbsp; &nbsp; // this next line is important&nbsp; &nbsp; [key: string]: string | number | undefined;}export class User {&nbsp; &nbsp; constructor(private data: UserProps) {}&nbsp; &nbsp; // number|string changed to number|string|undefined&nbsp; &nbsp; get(propName: string): number | string | undefined {&nbsp; &nbsp; &nbsp; &nbsp; return this.data[propName];&nbsp; &nbsp; }&nbsp; &nbsp; set(update: UserProps): void {&nbsp; &nbsp; &nbsp; &nbsp; Object.assign(this.data, update);&nbsp; &nbsp; }}
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答