【问题标题】:How to write typescript definition for is(constructor, instance) method如何为 is(constructor, instance) 方法编写打字稿定义
【发布时间】:2017-04-23 08:24:30
【问题描述】:

假设我有一个is 函数,基本上它就是这样工作的。

is(Array, []) // true
is(String, '') // true

因为它是一个 javascript 函数,我需要为它创建一个单独的打字稿定义。

现在我可以简单地实现下面的接口,

is(ctor: any, val: any): boolean;

但是这个定义还不够好,因为在我运行if(is(Array, stuffA)) { ... } 之后,if 块 内的typecirpt 编译器无法推断出stuffA 的类型。

我怎样才能使is 函数的类型断言起作用?

【问题讨论】:

    标签: javascript typescript type-assertion


    【解决方案1】:

    签名应如下所示:

    function is<T>(type: { new(): T }, obj: any): obj is T
    

    这将确保编译器理解正确的类型,即这个函数被视为a type guard。

    我也有这样的功能:

    function is<T>(obj: any, type: { new(): T }): obj is T {
        if (Number.isNaN(type as any) && Number.isNaN(obj)) {
            return true;
        }
    
        let objType: string = typeof obj;
        let nameRegex: RegExp = /Arguments|Function|String|Number|Date|Array|Boolean|RegExp/;
    
        if (obj && objType === "object") {
            return obj instanceof type;
        }
    
        let typeName: RegExpMatchArray = type.toString().match(nameRegex);
        if (typeName) {
            return typeName[0].toLowerCase() === objType;
        }
    
        return false;
    }
    

    (code in playground)


    编辑

    使用这个函数时,我们总是先传递一个实例,然后传递一个类。
    由于我们希望函数涵盖所有类型,我们将使用泛型,其中T 是传递实例的类型。

    如果T是实例的类型,那么类的类型是:

    { new(): T }
    

    这是描述构造器对象(也是一个类)的“打字稿方式”。
    更多可以在这里找到:Difference between the static and instance sides of classes。

    【讨论】:

    • 你能详细说明一下这个{ new(): T }吗?
    • 谢谢,这个话题很混乱,我稍后会试着理解它
    • 谢谢。你拯救了我的一天!
    • 我认为您可以通过这种方式实现您的 is 功能:return obj != null &amp;&amp; obj.constructor === type || obj instanceof type;
    猜你喜欢
    • 2018-08-24
    • 2017-03-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-26
    • 2019-06-30
    • 2019-09-08
    相关资源
    最近更新 更多