typescript - 如何编写 PickByValue 类型?

标签 typescript

Pick type 包含在 TypeScript 中。它的实现如下:

type Pick<T, K extends keyof T> = {
  [P in K]: T[P];
};

你会怎么写PickByValue键入以便以下工作:
type Test = {
  includeMe: 'a' as 'a',
  andMe: 'a' as 'a',
  butNotMe: 'b' as 'b',
  orMe: 'b' as 'b'
};

type IncludedKeys = keyof PickByValue<Test, 'a'>;
// IncludedKeys = 'includeMe' | 'andMe'

最佳答案

假设您打算 Test是这样的:

type Test = {
  includeMe: 'a',
  andMe: 'a',
  butNotMe: 'b',
  orMe: 'b'
};
并假设您想要 PickByValue<T, V>给出所有属于 V 的子类型的属性(这样 PickByValue<T, unknown> 应该是 T ),那么你可以定义 PickByValue像这样:
type PickByValue<T, V> = Pick<T, { [K in keyof T]: T[K] extends V ? K : never }[keyof T]>
type TestA = PickByValue<Test, 'a'>; // {includeMe: "a"; andMe: "a"}
type IncludedKeys = keyof PickByValue<Test, 'a'>; // "includeMe" | "andMe"
但如果您只想要 IncludedKeys ,然后您可以更直接地使用 KeysMatching<T, V> 执行此操作:
type KeysMatching<T, V> = {[K in keyof T]: T[K] extends V ? K : never}[keyof T];
type IncludedKeysDirect = KeysMatching<Test, 'a'> // "includeMe" | "andMe"
Playground link to code

关于typescript - 如何编写 PickByValue 类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55150760/

相关文章:

generics - Typescript 中的泛型是什么?

javascript - 如何访问 ng-template 中的元素? ( Angular 5)

javascript - TypeScript 扩展第三方库 moment.js

TypeScript 接口(interface)和实现

typescript - 为什么将 Omit<T, K> 等泛型应用于函数会导致它不可调用?

visual-studio - 在 Visual Studio 中编译 typescript 会出现错误 "Unexpected Token..."

Angular -将字节数组显示为图像

angular - 使用 TestBed 为具有依赖关系的 Angular 服务创建测试用例

typescript - 添加 vue3 后 npm run serve 不起作用

javascript - ' promise <void >' is not assignable to type ' promise <IListItem[]>