What is the type assertion operator for in TypeScript?

前端 未结 3 2010
野性不改
野性不改 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:48

    I assume you mean the : [type] notation after the parameters of a function? It doesn't appear to make a difference in the final .js file, but if you run the .ts file through the compiler, it will throw an error if it finds an unexpected input type for any type asserted parameters. Hope that answers your question.

    0 讨论(0)
  • 2020-12-20 15:52

    There are two forms of Typescript type assertions. Examples from the Typescript handbook here.

    1. Angle bracket syntax for type assertions (doesn't work within a tsx file):
    let strLength: number = (<string>someValue).length;
    
    1. as syntax for type assertions (works within ts or tsx alike):
    let strLength: number = (someValue as string).length;
    

    Type assertions override the (limited) type inference capabilities of the ever current version of Typescript, which can be a good thing if you are correct, but there is also a risk that your judgment is incorrect and TS will believe you. If there's a likely mismatch between what you infer and what TS infers, TS will still balk, then you can more strongly overrule the TS inference by as unknown as string.

    0 讨论(0)
  • 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 = <HTMLCanvasElement>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.

    0 讨论(0)
提交回复
热议问题