What is the type assertion operator for in TypeScript?

前端 未结 3 2015
野性不改
野性不改 2020-12-20 15:09

The spec doesn\'t say much about where the type assertion operator might be helpful in TypeScript. I didn\'t need it in my code. So I am curious what sort of problems it is

3条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-20 15:57

    It's somewhat like type casting however as it does not come with runtime support (its a compile time assertion only) TypeScript choses to call it 'Type Assertion'. Consider this example :

    var element1 = document.getElementById('canvas'); // Determined to be HTMLElement
    element1.getContext('2d'); // ERROR as it is HTMLElement 
    
    
    
    // Determined to be canvas due to your assertion
    var element2 = document.getElementById('canvas'); 
    element2.getContext('2d'); // Valid 
    

    You will need it whenever typescript type inference would prevent you to assign things around due to incompatible inferred types.

提交回复
热议问题