TypeScript
/Intermediate
Type Assertions
Definition
A mechanism that tells the compiler to treat a variable as a specific type, overriding its inferred or declared type.
Explain Like I'm New
Type Assertion is you pulling rank on the compiler. You look TypeScript in the eyes and say: 'I know you think this variable is an unknown HTML element, but I am the developer, and I guarantee you it is specifically an HTMLCanvasElement.'
Real World Example
Selecting a canvas from the DOM: `const canvas = document.getElementById('my-game') as HTMLCanvasElement;` so you can access `.getContext('2d')` without TS complaining.
Common Use Cases
- •DOM manipulation
- •Migrating JS to TS
- •Working with poorly typed 3rd-party libraries
Terminal Output
bash / terminal
// The DOM API returns a generic HTMLElement or null
// We ASSERT that we know it is an HTMLInputElement
const searchInput = document.getElementById('search') as HTMLInputElement;
// Now TS allows us to access the .value property specific to inputs
console.log(searchInput.value);
// Alternative syntax (Not recommended if using React/JSX because it clashes with tags)
const altInput = <HTMLInputElement>document.getElementById('search');
Interview Questions
basic
- What keyword is used for Type Assertions?
intermediate
- Does a Type Assertion actually change the variable at runtime?
advanced
- What is 'double assertion' (`as unknown as Type`)?