:
Declaring a variable with type
as string
let myStr: string;
Assertion
/Casting
Assertion
Telling the TypeScript compiler that you know more about the type of a value than it does
Type assertions
do not perform any runtime checks
and are purely a way to satisfy the compiler
as
or <>
Type of myStr
is determine by type assertion as there is no explicit type defined prior
myStr
could be something passed dynamically as a function parameterlet strLength: number = (myStr as string).length;
Variable with missing type can later be typed with casting
// untyped initialization let value: any = "Hello World"; // assertion/casting let length: number = (value as string).length;
JSX
It's important to note that the angle bracket syntax for type assertions (<type>value
) can conflict with JSX syntax in TypeScript
as
keyword for type assertions instead
as
and <>
are same in context of type assertion// (discouraged) Use on the left side for assertion/casting var foo: any; var bar = <string>foo; // same as using `as` keyword to cast type var foo = bar as string;
!
)Way of requiring that the attribute on an object should always exist
// x in param is optional function liveDangerously(x?: number | null) { // x to always exist via assertion console.log(x!.toFixed()); }