Interface type check with Typescript

前端 未结 17 1284
灰色年华
灰色年华 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条回答
  •  旧时难觅i
    2020-11-22 14:32

    You can achieve what you want without the instanceof keyword as you can write custom type guards now:

    interface A{
        member:string;
    }
    
    function instanceOfA(object: any): object is A {
        return 'member' in object;
    }
    
    var a:any={member:"foobar"};
    
    if (instanceOfA(a)) {
        alert(a.member);
    }
    

    Lots of Members

    If you need to check a lot of members to determine whether an object matches your type, you could instead add a discriminator. The below is the most basic example, and requires you to manage your own discriminators... you'd need to get deeper into the patterns to ensure you avoid duplicate discriminators.

    interface A{
        discriminator: 'I-AM-A';
        member:string;
    }
    
    function instanceOfA(object: any): object is A {
        return object.discriminator === 'I-AM-A';
    }
    
    var a:any = {discriminator: 'I-AM-A', member:"foobar"};
    
    if (instanceOfA(a)) {
        alert(a.member);
    }
    

提交回复
热议问题