首页 > 解决方案 > 隐含地具有“任何”类型,因为 typescript 中的类型表达式

问题描述

我有这样的课:

interface UserProps {
  name: string
  age: number
}

export class User {
  constructor(private data: UserProps) {}

  get(propName: string): number | string {
    return this.data[propName]
  }
}

而且我不知道为什么会出现此错误:“元素隐式具有'any'类型,因为'string'类型的表达式不能用于索引'UserProps'类型。
没有带有'string'类型参数的索引签名' 在类型 'UserProps' 上找到

有什么建议吗?

标签: javascripttypescript

解决方案


发生错误是因为您不能使用 anystring作为键,只能使用子集(nameage)。设置keyof UserProps为 的类型propName

interface UserProps {
  name: string
  age: number
}

export class User {
  constructor(private data: UserProps) {}

  get<T extends keyof UserProps>(propName: T): UserProps[T] {
    return this.data[propName]
  }
}

推荐阅读