我正在嘗試提取keyof與事件處理程式模式匹配的介面(使用)的鍵- 即(CustomEvent) => void.
我有一種方法似乎有效并且只提取匹配的鍵(CustomEvent) => void,但是,它也提取型別為 的鍵() => void。
有沒有辦法只提取符合型別的鍵(CustomEvent) => void?
該方法基于問題 Filter interface keys for a sub-list of keys based on value type and Typescript : Filter on keyof type parameter
在下面的例子中
export interface JayCustomEvent {}
type EventHandler = (e: JayCustomEvent) => void;
type FilteredKeys<T, U> = { [P in keyof T]: P extends string ? (T[P] extends U ? P : never) : never}[keyof T];
interface AComponentEvent extends JayCustomEvent {}
interface AComponent {
anEvent(e: AComponentEvent): void,
noParamFunction(): void,
someOtherFunction(a: number): void
someProp: string
}
let a: FilteredKeys<AComponent, EventHandler> = 'anEvent'
let b: FilteredKeys<AComponent, EventHandler> = 'noParamFunction'
let c: FilteredKeys<AComponent, EventHandler> = 'someOtherFunction'
let d: FilteredKeys<AComponent, EventHandler> = 'someProp'
我希望分配a作業,而b,c并且d不應該。但是,賦值a和b是有效的,而 onlyc和d不是。
uj5u.com熱心網友回復:
您的映射實用程式看起來不錯。
我想你可能會驚訝地發現具有較低數量的函式是兼容的較高數量的函式的子型別。考慮以下示例:
type AssignableTo<T, U> = T extends U ? true : false;
type Fn0Params = () => void;
type Fn1Param = (p: unknown) => void;
declare const ex1: AssignableTo<Fn0Params, Fn1Param>;
ex1 // true
type Fn0ParamsNever = (...args: never) => void;
declare const ex2: AssignableTo<Fn0ParamsNever, Fn1Param>;
ex2 // false
因此,通過鍵入您的noParamFunctionas 具有 type 引數never,您可以防止將其分配給EventHandler:
noParamFunction(...args: never): void
TS游樂場
垂直于您的問題:如果您實際上正在使用
CustomEvents,那么您可能想要使用(event: CustomEvent<JayCustomEvent>) => void
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/386282.html
