打字稿声明具有属性的函数

时间:2017-09-30 10:36:19

标签: typescript

我正在写一个library,我想把它移植到打字稿。

目前它看起来像这样:

index.js

WHERE HName=Sire

等等。

我编写了一个描述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 => ...

这是有道理的,因为对象的声明是分开的。

如何构建既是方法又有方法的对象?

3 个答案:

答案 0 :(得分:2)

您无法同时实现某个功能及其属性。您可以先定义函数并将其断言为Is并定义其余方法:

const is = ((val: any) => typeof (val)) as any as Is;

is.null = (val) => true;
is.undefined = (val) => true;

或使用工厂功能创建Is

function createIs(): Is {
    const is = ((val: any) => {
        return "";
    }) as Is;
    is.null = (val) => true;
    is.undefined= (val) => true;
    return is;
}

const is: Is = createIs();

答案 1 :(得分:2)

如果您想让类型检查器满意,可以使用Object.assign()返回完整格式的Is对象,而无需分阶段构建它:

const is: Is = Object.assign(
  (val: any) => typeof val,
  {
    undefined: (val: any) => typeof val === 'undefined',
    null: (val: any) => (val === null)
    // ...
  }
);

当然,如果您不想更改代码的结构,那么您可以像@Saravana建议并使用type assertion来通知类型检查器is肯定是一个Is,即使它在你完成构建之前在技术上不是一个。

无论哪种方式都有效,但我更喜欢Object.assign()方法,因为类型检查器会在您忽略实现某些内容时发出警告:

// error, "undefined" is missing
const is: Is = Object.assign(
  (val: any) => typeof val,
  {
    null: (val: any) => (val === null)
    // ...
  }
);

虽然类型断言方法不会:

const is = ((val: any) => typeof val) as any as Is;
is.null = (val) => val === null;
// no error

而类型断言方法则不会。由你决定。希望有所帮助;祝你好运!

答案 2 :(得分:1)

您需要做的就是提供可选的属性:

finally

现在您可以安全地将其定义为type TypeQueryMethod = (val: any) => boolean; interface Is { (val: any): string; undefined?: TypeQueryMethod; null?: TypeQueryMethod; ... }

Is