ThisType and Template Literal Types

1. Welcome and Icebreaker:

  • If you could create a template for any message or set the type of this in any context, what would you do?

2. Outline the Session:

  • We’ll learn about ThisType and template literal types in TypeScript.
  • Learning Outcomes: Understand how to use ThisType for context typing and template literals for advanced string types.
  • Let’s get creative with types!

3. Concept Explanation:

  • ThisType<T>: Used in object literals to specify the type of this inside methods.
  • Template Literal Types: Create string types using template literals, allowing for powerful type combinations.
  • Syntax:
    type Greeting<T extends string> = `Hello, ${T}`;
    type User = { name: string } & ThisType<{ sayHello(): void }>;
    

4. Live Coding Demonstration:

// Template literal types
type EventName = `on${Capitalize<string>}`;
type ButtonEvent = `onClick` | `onHover`;

// ThisType example
const obj: ThisType<{ x: number }> = {
  // ...
};

// Using ThisType in an object literal
const calculator = {
  x: 0,
  add(y: number) {
    this.x += y;
    return this.x;
  }
};
calculator.add(5);

// Template literal type for IDs
type ID<T extends string> = `${T}_id`;
type UserID = ID<'user'>; // 'user_id'

5. Tasks:

  • Short Exercise:
    1. Create a template literal type for event names like onSave, onDelete.
    2. Use ThisType to specify the type of this in an object literal with a method.
    3. Try combining template literal types with union types.