Execute Program

TypeScript Basics: Generic Object Types

Welcome to the Generic Object Types lesson!

This lesson is shown as static text below. However, it's designed to be used interactively. Click the button below to start!

  • We've seen that the Array type is generic: there's a "hole" in it. Array<number> is an array of numbers. Array<string> is an array of strings. Etc.

  • We can create our own generic object types with type holes like this. For example, a pair of pants has two front pockets. Let's allow each to hold an item of any type.

  • >
    type Pants<T> = {
    left: T
    right: T
    };
  • Note: this code example reuses elements (variables, etc.) defined in earlier examples.
    >
    let pants: Pants<string> = {
    left: 'phone',
    right: 'keys',
    };
    pants.left;
    Result:
    'phone'Pass Icon
  • In any given pair of pants, the type parameter T must always refer to the same type. This means that the left and right pockets must hold values of the same type. Trying to put different types in the pockets will cause a type error.

  • Note: this code example reuses elements (variables, etc.) defined in earlier examples.
    >
    let pants: Pants<number> = {
    left: 4,
    right: 5,
    };
    pants.left;
    Result:
    4Pass Icon
  • Note: this code example reuses elements (variables, etc.) defined in earlier examples.
    >
    let pants: Pants<string> = {
    left: 'phone',
    right: 5,
    };
    pants.left;
    Result:
    type error: Type 'number' is not assignable to type 'string'.Pass Icon
  • The type variable T can refer to different types in different pairs of pants. It's fine as long as each pair of pants has a single, consistent type for T.

  • Note: this code example reuses elements (variables, etc.) defined in earlier examples.
    >
    const pants1: Pants<string> = {
    left: 'phone',
    right: 'keys',
    };
    const pants2: Pants<number> = {
    left: 4,
    right: 5,
    };
    [pants1.left, pants2.right];
    Result:
    ['phone', 5]Pass Icon
  • Generic object types can have more than one type parameter. We can use this to model pants where the pockets contain different types.

  • >
    type Pants<T1, T2> = {
    left: T1
    right: T2
    };
  • Note: this code example reuses elements (variables, etc.) defined in earlier examples.
    >
    let pants: Pants<string, number> = {
    left: 'phone',
    right: 5,
    };
    pants.left;
    Result:
    'phone'Pass Icon
  • Note: this code example reuses elements (variables, etc.) defined in earlier examples.
    >
    let pants: Pants<boolean, string> = {
    left: true,
    right: 'phone',
    };
    pants.left;
    Result:
    truePass Icon
  • Note: this code example reuses elements (variables, etc.) defined in earlier examples.
    >
    let pants: Pants<string, boolean> = {
    left: 'phone',
    right: 'keys',
    };
    pants.left;
    Result:
    type error: Type 'string' is not assignable to type 'boolean'.Pass Icon