Interface type check with Typescript

前端 未结 17 1401
灰色年华
灰色年华 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:33

    How about User-Defined Type Guards? https://www.typescriptlang.org/docs/handbook/advanced-types.html

    interface Bird {
        fly();
        layEggs();
    }
    
    interface Fish {
        swim();
        layEggs();
    }
    
    function isFish(pet: Fish | Bird): pet is Fish { //magic happens here
        return (pet).swim !== undefined;
    }
    
    // Both calls to 'swim' and 'fly' are now okay.
    
    if (isFish(pet)) {
        pet.swim();
    }
    else {
        pet.fly();
    }
    

提交回复
热议问题