www.typescripttutorial.net/typescript-tutorial/type-assertions/
1 Users
0 Comments
11 Highlights
0 Notes
Tags
Top Highlights
Type assertions instruct the TypeScript compiler to treat a value as a specified type. It uses the as keyword to do so:
expression as targetType
type assertion is also known as type narrowing. It allows you to narrow a type from a union type. Let’s see the following simple function:
number | string
let netPrice = getNetPrice(100, 0.05, true) as string;
let netPrice = getNetPrice(100, 0.05, false) as number
Note that a type assertion does not carry any type casting. It only tells the compiler which type it should apply to a value for the type checking purposes.
<targetType> value
let netPrice = <number>getNetPrice(100, 0.05, false);
Note that you cannot use angle bracket syntax <> with some libraries such as React. For this reason, you should use the as keyword for type assertions.
ype assertions use the as keyword or an angle bracket <> syntax.
Glasp is a social web highlighter that people can highlight and organize quotes and thoughts from the web, and access other like-minded people’s learning.