If you want to delve into the world of TypeScript, be sure to check out this page from the TypeScript handbook. The section on Type assertions covers the <Type>
syntax, which is key to understanding variable types in TypeScript.
The :Type
syntax indicates the type of a variable, for example:
let example: string = "This is a string";
let exampleNumber: number = 12;
However, TypeScript is smart and can often infer types without explicit declarations, as shown in this simplified version:
let example = "This is a string";
let exampleNumber = 12;
At times, TypeScript may default to an any
type, allowing for flexibility in variable typing. By utilizing both the and :Type syntax, you can enforce strong typing, like so:
function test(arg: any): number {
// Treat arg as a string;
let example: string = arg;
// Treat arg as a string through Type assertion.
let otherExample = <string> arg;
// Returns arg as a number to enforce strong typing.
return arg;
}
// Nr will be inferred as a number by the compiler.
let nr = test(12);