【发布时间】:2021-09-22 09:10:46
【问题描述】:
我有一个函数类型如下:
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类型的键。所以你想要这个问答中的KeysMatching类型:How to write PickByValue type? -
我更新了我的问题,使其更加清晰。我说的是值的类型。我刚刚回答了我自己的问题????
-
我看不出您的问题与您自己的答案之间有任何关系。通过添加第二个类型参数,您打破了提供一个类型参数的用例示例,并且您的类型参数
PK仅受keyof E限制,因此没有什么可以阻止它成为'name'或'age'。 -
你是对的。我最初的问题从我的脑海中消失了,我发布了一个适用于我现实生活案例的解决方案。谢谢你提醒我。
-
为什么
getByPrimaryKey<User>(users, 'age') // NOT OK because age is a number不行?
标签: typescript typescript-generics