TypeScript: Type assertion

By Xah Lee. Date: . Last updated: .

Type assertions (force a type)

two syntax for this:

val as type

or

<type> val (this syntax cannot be used in .tsx files)

example

const xx = ((<HTMLInputElement> searchBox).value)
const xx = ((searchBox as HTMLInputElement).value);

usually you need to do this with DOM objects.

Non-null Assertion Operator (Postfix !)

put a ! at the end of expression.

val!

const ff = (x: number | null) => {
 return console.log(x!.toFixed());
};