javascript - 隐含地具有“任何”类型,因为 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' 上找到“
有什么建议吗?
解决方案
发生错误是因为您不能使用 anystring
作为键,只能使用子集(name
和age
)。设置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]
}
}
推荐阅读
- python - 关于矩阵对角化的 Python 例程
- php - 正则表达式 - 排除带有单词的行(php)
- python - ValueError:没有为任何变量提供梯度 - Tensorflow 2.0/Keras
- eclipse - 为 Maven Web 项目启动 Tomcat 服务器的问题
- java - 在 Java 中重载和覆盖静态和非静态方法
- ios - 更新 SCNNode 镜像
- react-native - 'expo-splash-screen-command'命令后的expo裸应用程序崩溃
- php - Laravel 数据库查询读取不使用 get
- sql - 信息架构中的 referential_constraints.unique_constraint_* 列的 NULL 值
- r - geom_path 函数连接来自不同试验的观察结果