The TypeScript `as` operator tells the compiler to treat an expression as a specified type. It does not change the value at runtime. Use it when the compiler cannot infer a type you know is appropriate—but check that assumption: an incorrect assertion can leave a runtime error that TypeScript would otherwise help prevent. section 3.4.2
Allowing an ambiguous operation
For a `number | string` parameter, TypeScript rejects `param + 100` as ambiguous. Writing `(param as any) + 100` permits it, but `any` also stops useful type checking. The runtime results still differ: `1` produces `101`, while `"London"` produces `"London100"`. section 3.4.2
Listing 3.19. Addressing the ambiguity in the main.ts file in the src folder
function myFunction(param: number | string) {
if (typeof(param) == "number" || typeof(param) == "string") {
let result = (param as any) + 100;
console.log("My result: " + result);
} else {
throw ("Expected a number or a string: " + param)
}
}
myFunction(1);
myFunction("London");
The listing shows where `as any` is applied to the union-typed value before addition. section 3.4.2
An assertion can also help with a narrower result. When filtering a mixed array for numbers and then reducing it to a sum, the reducer uses `val as number` because the compiler does not infer the needed type from this operation. The example totals `100` and `200` to produce `300`. section 4.3.4
Listing 4.18. Processing a data array in the main.ts file in the src folder
let myArray: (number | string | boolean)[] = [100, "Adam", true];
let otherArray = [...myArray, 200, "Bob", false];
let sum: number = otherArray
.filter(val => typeof(val) == "number")
.reduce((total: number, val) => total + (val as number), 0)
console.log(`Sum: ${sum}`);
The array pipeline places the assertion at the point where the reducer adds each filtered value. section 4.3.4
Prefer checking a value when its runtime type is uncertain. A `typeof` check allows a `number | string` value to use number-only methods in the number branch. In an Angular event handler, an `instanceof HTMLInputElement` check similarly establishes that the target has a `value` property without using `any`. Type assertions cannot be performed in Angular templates; put type handling in the component class. section 3.4.2 section 13.2.2


