2017-09-30 143 views
1

我在写一个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; 
    ... 
} 

当我尝试使用该类型的标记isconst is: Is = value => ...

它抛出一个错误:

Type '(value: any) => string' is not assignable to type 'Is'. 
Property 'undefined' is missing in type '(value: any) => string'. 

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

你如何构建这样一个既是方法又有方法的对象?

回答

1

您不能同时实现函数及其属性。你可以先定义函数,并声称要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(); 
+0

你应该可以使用'Object.assign()'创建一个没有类型断言的'Is'。 – jcalz

0

如果你想类型检查快乐,你可以使用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 

而类型断言方法不会。随你便。希望有所帮助;祝你好运!