Single assertions are allowed if the types are compatible in one direction. e.g.:
type Point2D = { x: number, y: number };
type Point3D = { x: number, y: number, z: number };
let point2: Point2D = { x: 0, y: 0 };
let point3: Point3D = { x: 10, y: 10, z: 10 };
point3 = point2; // Error
point3 = point2 as Point3D; // Ok: I trust you
If they are not compatibility in either direction then TypeScript will not allow the assertion e.g.:
type Point2D = { x: number, y: number };
type Person = { name: string, email: string };
let point2: Point2D = { x: 0, y: 0 };
let person: Person = { name: 'john', email: 'john@example.com' };
point2 = person; // Error
point2 = person as Point2D; // Error: I don't trust you enough
Double Assertion
We can assert to unknown
as a middle step. Since unknown is compatible with all types, TypeScript allow the next assertion e.g.:
type Point2D = { x: number, y: number };
type Person = { name: string, email: string };
let point2: Point2D = { x: 0, y: 0 };
let person: Person = { name: 'john', email: 'john@example.com' };
point2 = person; // Error
point2 = person as unknown as Point2D; // Ok: I trust you
Further
Some people use as any
(instead of as unknown
). They are both equivalent, but prefer using unknown
as it is common to search a codebase for any
as a sign of code smell 💩.
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4