我有一个函数的类型如下:
const getByPrimaryKey = <E>(list: E[], primaryKey: keyof E): E => {...}
我可以为与primaryKey
相关联的值添加类型验证吗?例如:
interface User {
id: string
name?: string
age: number
}
const users: User[] = [{id: '1', age: 1}]
getByPrimaryKey<User>(users, 'id') // OK since id is a string
getByPrimaryKey<User>(users, 'name') // NOT OK because name maybe undefined
getByPrimaryKey<User>(users, 'age') // NOT OK because age is a number
keyof T
将是'id' | 'name' | 'age'
,它们都是字符串;我认为你的意思是想要一个关联值类型为string
的键。因此,你需要从这个 Q&A 中获取KeysMatching
类型:如何编写 PickByValue 类型? - kaya3PK
仅受keyof E
的限制,因此没有任何阻止它成为'name'
或'age'
。 - kaya3getByPrimaryKey<User>(users, 'age') // NOT OK because age is a number
不行? - captain-yossarian from Ukraine