gpt4 book ai didi

typescript - 如何编写 PickByValue 类型?

转载 作者:行者123 更新时间:2023-12-03 16:03:57 26 4
gpt4 key购买 nike

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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com