我在玩TypeScript时发现,在可调用函数上应用Omit<T, K>
会使其不再可调用:
declare function myCallableFunction(): void;
myCallableFunction(); // valid
type NonOmittedFunction = typeof myCallableFunction;
declare const myNonOmittedFunction: NonOmittedFunction;
myNonOmittedFunction(); // valid
type OmittedFunction = Omit<typeof myCallableFunction, 'foobar'>;
declare const myOmittedFunction: OmittedFunction;
myOmittedFunction(); // This expression is not callable.
// Type 'OmittedFunction' has no call signatures.
为什么会这样?
以下是一个精心设计的示例,您可能希望在其中执行以下操作:
declare type CallCountingFunction = (() => void) & { count: number }
const myFunction: CallCountingFunction = (() => {
const x = () => {};
x.count = 0;
return x;
})()
myFunction.count; // valid
myFunction() // valid
type OmittedFunction = Omit<CallCountingFunction, 'count'>;
declare const myOmittedFunction: OmittedFunction;
myOmittedFunction(); // This expression is not callable.
// Type 'OmittedFunction' has no call signatures.
对于涉及重新映射的all种通用实用程序类型(例如Partial<T>
和Required<T>
),这似乎是正确的.