我正在尝试为一个JavaScript库创建类型定义,该库的模式非常允许。
特别是,我遇到了一种情况,其中类型可以是函数,也可以是具有handler
属性作为函数的对象:
type SpecificFunc = (arg: string) => number;
type VeryPermissiveObject = {
name?: string;
type?: number;
handler?: SpecificFunc;
[key: string]: any;
}
这是一个极简主义的示例,但它忠实于这种情况。如您所见,VeryPermissiveObject
是非常允许的,并且可以接受任何类型的任何键(name
,type
和handler
除外)类型。
在JavaScript代码中,测试很简单,看起来像这样:
if (typeof objOrFunc === "function") {
// Do something
}
现在,我做了这两种类型的联合:
type OneOfThem = SpecificFunc | VeryPermissiveObject;
并尝试使用它:
// I would like test1 to report an error stating that parameter 'arg' of type `number` is not assignable to `string`
const test1: OneOfThem = (arg: number) => { return "" };
如您所见,函数test1
不满足SpecificFunc
的类型,但TypeScript仍会接受它,因为它与VeryPermissiveObject
相匹配。
Playground Link of this toy example
我想知道是否有一种方法可以稍微改变这种情况,以便TypeScript不能与VeryPermissiveObject
匹配函数。