Interface type check with Typescript

前端 未结 17 1425
灰色年华
灰色年华 2020-11-22 14:09

This question is the direct analogon to Class type check with TypeScript

I need to find out at runtime if a variable of type any implements an interface. Here\'s my

17条回答
  •  生来不讨喜
    2020-11-22 14:28

    In TypeScript 1.6, user-defined type guard will do the job.

    interface Foo {
        fooProperty: string;
    }
    
    interface Bar {
        barProperty: string;
    }
    
    function isFoo(object: any): object is Foo {
        return 'fooProperty' in object;
    }
    
    let object: Foo | Bar;
    
    if (isFoo(object)) {
        // `object` has type `Foo`.
        object.fooProperty;
    } else {
        // `object` has type `Bar`.
        object.barProperty;
    }
    

    And just as Joe Yang mentioned: since TypeScript 2.0, you can even take the advantage of tagged union type.

    interface Foo {
        type: 'foo';
        fooProperty: string;
    }
    
    interface Bar {
        type: 'bar';
        barProperty: number;
    }
    
    let object: Foo | Bar;
    
    // You will see errors if `strictNullChecks` is enabled.
    if (object.type === 'foo') {
        // object has type `Foo`.
        object.fooProperty;
    } else {
        // object has type `Bar`.
        object.barProperty;
    }
    

    And it works with switch too.

提交回复
热议问题