我有一个函数类型如下:
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
最佳答案
您需要结合几个 conditional types .
获取所有非可选键:
type RequiredKeys<T> = { [K in keyof T]-?: ({} extends { [P in K]: T[K] } ? never : K) }[keyof T];
获取具有特定类型值的所有键:
type TypeMatchingKeys<T, V> = { [K in keyof T]: T[K] extends V ? K : never }[keyof T];
然后你可以使用两者的交集:
type NonOptionalTypeMatchingKeys<T, V> = TypeMatchingKeys<T, V> & keyof Pick<T, RequiredKeys<T>>;
const getByPrimaryKey = <E>(list: E[], primaryKey: NonOptionalTypeMatchingKeys<E, string>): E => {
...
}
关于 typescript :是否可以强制 'keyof T' 成为字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68360282/