A type assertion tells TypeScript to check an expression as a specified type. Write the expression followed by `as` and the type. This is useful when you know something about a value that the compiler cannot establish, but it does not convert or validate the value at runtime. section 7.4 section 2.4.3
Select a type from a union
In `src/index.ts`, `calculateTax(100, false)` returns a number, while `calculateTax(100, true)` returns a formatted string. The declared return type is `string | number`, so assertions permit operations specific to each result: `let taxNumber = calculateTax(100, false) as number;` and `let taxString = calculateTax(100, true) as string;`. The first can use `toFixed(2)`; the second can use `charAt(0)`. These assertions depend on the calls behaving as expected. section 7.4
Listing 7.23 Using type assertions in the index.ts file in the src folder
function calculateTax(amount: number, format: boolean): string | number {
const calcAmount = amount * 1.2;
return format ? `$${calcAmount.toFixed(2)}` : calcAmount;
}
let taxNumber = calculateTax(100, false) as number;
let taxString = calculateTax(100, true) as string;
console.log(`Number Value: ${taxNumber.toFixed(2)}`);
console.log(`String Value: ${taxString.charAt(0)}`);
The complete `src/index.ts` listing shows the union return type, both assertions, and the type-specific method calls together. section 7.4
Keep the compiler's warning and the runtime value separate:
- An assertion from `string | number` directly to `boolean` produces an error because `boolean` is not an expected type. Usually, correct the union or the assertion instead. section 7.4.1
- A double assertion through `any` can suppress that warning, but it cannot turn a number into a boolean: the example still prints `120`. Use this escape hatch only when you can take responsibility for the actual value. section 7.4.1
Read a DOM event target
In `src/productItem.tsx`, a quantity-change handler reads `Number((ev.target as HTMLSelectElement).value)`. The assertion lets the handler access the select element's `value`; `Number(...)`, not the assertion, performs the conversion used for the quantity. section 16.8.1
Assertions also appear where inference is too restrictive: an empty array may be inferred as `never` under the shown `strictNullChecks` configuration, and a conditional return type may require an `as any` assertion when the compiler cannot correlate its branches. Consider whether a better initialization or type description can avoid overriding the checker. section 9.2.3 section 13.6.2




