typescript :是否可以强制 'keyof T' 成为字符串?

标签 typescript typescript-generics

我有一个函数类型如下:

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/

相关文章:

node.js - Deno:如何处理异常

Angular2 DI : Inject a new value on every injection?

Typescript 无法弄清楚通用性

typescript - 为什么 TypeScript 允许在具有不同参数类型的自定义泛型类型之间进行分配?

reactjs - 根据对象中键的值定义类型

typescript - Cypress 自定义 TypeScript 命令不是函数

typescript - 如何正确处理 Vuejs 中异步事件监听器中的拒绝错误?

JayData 库和 JaySvcUtil 生成的代码的 TypeScript 编译错误

reactjs - typescript 语法

带有通用类型的 Typescript 装饰器