我在写一个library,我想将它移植到typescript。Typescript声明一个函数的属性
目前,它看起来就像是:
index.js
const is = value => {
... do some returns here
}
is.number = x => typeof x === 'number'
is.bla = x => typeof x === 'bla'
等。
我写了一个接口描述is
及其所有方法。
type TypeQueryMethod = (val: any) => boolean;
interface Is {
(val: any): string;
undefined: TypeQueryMethod;
null: TypeQueryMethod;
...
}
当我尝试使用该类型的标记is
:const is: Is = value => ...
它抛出一个错误:
Type '(value: any) => string' is not assignable to type 'Is'.
Property 'undefined' is missing in type '(value: any) => string'.
这是有道理的,因为对象的声明是分裂。
你如何构建这样一个既是方法又有方法的对象?
你应该可以使用'Object.assign()'创建一个没有类型断言的'Is'。 – jcalz