Type Assertions

1. Welcome and Icebreaker:

  • If you could tell the computer “trust me, I know what I’m doing” in any situation, when would you use it?

2. Outline the Session:

  • We’ll learn about type assertions in TypeScript: what they are, how to use them, and when to avoid them.
  • Learning Outcomes: Understand how to use type assertions to override TypeScript’s inferred types, and the risks involved.
  • Let’s see how to use this feature safely!

3. Concept Explanation:

  • Type Assertions tell TypeScript to treat a value as a specific type, overriding its inferred type.
  • Syntax:
    • Angle-bracket: <Type>value (not allowed in .tsx files)
    • as syntax: value as Type (preferred, especially in React/JSX)
  • Use Cases:
    • When you know more about a value’s type than TypeScript can infer (e.g., working with DOM elements, third-party data, or after narrowing types).
  • Risks:
    • Type assertions do not perform runtime checks. If you assert the wrong type, you may get runtime errors.
    • Use sparingly and only when you’re certain about the type.

4. Live Coding Demonstration:

// Using 'as' syntax
let someValue: unknown = "Hello, TypeScript!";
let strLength: number = (someValue as string).length;
console.log(strLength);

// Angle-bracket syntax (not in .tsx files)
let anotherValue: any = 123;
let numValue: number = <number>anotherValue;
console.log(numValue);

// Example with DOM (in browser environment)
// const input = document.getElementById('myInput') as HTMLInputElement;
// input.value = 'New value';

// Type assertion after narrowing
function process(value: string | number) {
  if (typeof value === "string") {
    // TypeScript knows value is string here
    console.log((value as string).toUpperCase());
  } else {
    // TypeScript knows value is number here
    console.log((value as number).toFixed(2));
  }
}
process("test");
process(42);

5. Tasks:

  • Short Exercise:
    1. Declare a variable of type unknown and assign it a string value. Use a type assertion to get its length.
    2. Use the angle-bracket syntax to assert a variable of type any as a number and print its value.
    3. Write a function that takes a parameter of type string | number and uses a type assertion to treat it as a string if it’s a string.
    4. (Optional) In a browser environment, use a type assertion to access the value property of an input element by its ID.