gpt4 book ai didi

typescript - 根据值类型过滤键子列表的接口(interface)键

转载 作者:行者123 更新时间:2023-12-05 02:50:38 25 4
gpt4 key购买 nike

问题

给定一个被视为 map 的 TypeScript 接口(interface)(将唯一键类型与非唯一值类型相关联),可以提取映射到指定值类型的键类型?

作为一个具体的例子,从 lib.dom.d.ts 中的 WindowEventMap 开始......

interface WindowEventMap 
extends GlobalEventHandlersEventMap, WindowEventHandlersEventMap {
"abort": UIEvent;
"afterprint": Event;
"beforeprint": Event;
"beforeunload": BeforeUnloadEvent;
"blur": FocusEvent;
// ...
}

有一个内置的运算符keyof 用于获取所有的 key :

type FullKeyList = keyof WindowEventMap;
// gives: FullKeyList = "'abort' | 'afterprint' | 'beforeprint' | ..and 93 more"

是否有一些表达式可能只过滤映射到值类型 KeyboardEvent 的键?:

// Goal:
type SubKeyList = SomeExpression<WindowEventMap, KeyboardEvent>;
// would give: SubKeyList = "'keyup' | 'keypress' | 'keydown'"

解决方案尝试

TypeScript 具有条件类型表达式:

T extends U ? X : Y

所以这是一个合理的尝试:

type Filter<K extends keyof M, V, M> = M[K] extends V ? K : never;

它过滤个别类型:

// Passes this test:
type FilteredExample1 = Filter<'keyup', KeyboardEvent, WindowEventMap>;
// gives FilteredExample1 = "'keyup'"

// Passes this test:
type FilteredExample2 = Filter<'blur', KeyboardEvent, WindowEventMap>;
// gives FilteredExample2 = "never"

它可以过滤类型的联合并返回一个新的联合吗?开始看起来不错:

// Passes this test:
type FilteredUnionExample1 = Filter<'keyup' | 'keydown', KeyboardEvent , WindowEventMap>;
// gives FilteredUnionExample1 = "'keyup' | 'keydown'"

但是,如果一个或多个联合体成员失败,则联合体失败:

// Fails this test:
type FilteredUnionExample2 = Filter<'keyup' | 'keydown' | 'blur', KeyboardEvent, WindowEventMap>;
// gives FilteredUnionExample2 = "never" (and not sub-union "'keyup' | 'keydown'")

// And so, it also fails the end-goal usage:
type AllKeysUnion = keyof WindowEventMap;
type FilteredUnionExample3 = Filter<AllKeysUnion, KeyboardEvent , WindowEventMap>;
// gives FilteredUnionExample3 = "never" (not sub-union "'keyup' | 'keypress' | 'keydown'")

这个问题有解决办法吗?

最佳答案

我通常称之为KeysMatching:

type KeysMatching<T, V> = {[K in keyof T]: T[K] extends V ? K : never}[keyof T];

type SubKeyList = KeysMatching<WindowEventMap, KeyboardEvent>
// type SubkeyList = "keydown" | "keypress" | "keyup"

希望对您有所帮助;祝你好运!

Playground link to code

关于typescript - 根据值类型过滤键子列表的接口(interface)键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63553724/

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