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 supposed to solve. Any ideas?
-
2This gitbook have a chapter for it. In short, it's an assertion of "I know better about the type" from programmer to compiler.Jokester– Jokester2017-02-02 08:30:25 +00:00Commented Feb 2, 2017 at 8:30
-
2024 update, the gitbook link in @Jokester 's comment was updated to: !https://basarat.gitbook.io/typescript/type-system/type-assertionLeoPkm2-1– LeoPkm2-12024-08-16 08:46:25 +00:00Commented Aug 16, 2024 at 8:46
3 Answers
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.
2 Comments
function eraseType(whatever: any) { return whatever; } function test() { var htmlElement = document.getElementById('canvas'); var canvas:HTMLCanvasElement = eraseType(htmlElement); }There are two forms of Typescript type assertions. Examples from the Typescript handbook here.
- Angle bracket syntax for type assertions (doesn't work within a
tsxfile):
let strLength: number = (<string>someValue).length;
assyntax for type assertions (works withintsortsxalike):
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.
Comments
Angle bracket syntax for type assertions like:
let content: any = "This is a stack overflow tutorial";
let output: number = (<string> content). length;
let output1: number = (content as string). length;
console.log(output);
In the above example we have a variable content of type any. We assign a value of this variable to another variable called output. However we know that code is of type string, even though it has been declared as any.