Class type check in TypeScript

前端 未结 3 1070
星月不相逢
星月不相逢 2020-11-30 00:28

In ActionScript, it is possible to check the type at run-time using the is operator:

var mySprite:Sprite = new Sprite(); 
trace(mySprite is Sprite); // true          


        
3条回答
  •  自闭症患者
    2020-11-30 00:39

    TypeScript have a way of validating the type of a variable in runtime. You can add a validating function that returns a type predicate. So you can call this function inside an if statement, and be sure that all the code inside that block is safe to use as the type you think it is.

    Example from the TypeScript docs:

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

    See more at: https://www.typescriptlang.org/docs/handbook/advanced-types.html

提交回复
热议问题