Execute Program

TypeScript Basics: Object Types

Welcome to the 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!

  • In JavaScript, myObject.someProperty will return undefined if someProperty doesn't exist. This has caused an uncountable number of errors in production applications. The most common symptom is the "undefined is not a function" error when we do myObject.someProperty().

  • TypeScript's object types let us catch this type of error at compile time. No more finding these bugs because they fail in production!

  • An object type specifies each property's name and type.

  • >
    type User = {
    email: string
    admin: boolean
    };
    let amir: User = {
    email: 'amir@example.com',
    admin: true,
    };
    amir.admin;
    Result:
    truePass Icon
  • Object types require that all properties are present. (You can write type error if an example will result in a type error.)

  • >
    type User = {email: string, admin: boolean};
  • Note: this code example reuses elements (variables, etc.) defined in earlier examples.
    >
    let cindy: User = {email: 'cindy@example.com'};
    cindy.email;
    Result:
    type error: Property 'admin' is missing in type '{ email: string; }' but required in type 'User'.Pass Icon
  • They also require properties to match the property types in the type definition.

  • Note: this code example reuses elements (variables, etc.) defined in earlier examples.
    >
    let cindy: User = {email: 'cindy@example.com', admin: true};
    cindy.admin;
    Result:
    truePass Icon
  • Note: this code example reuses elements (variables, etc.) defined in earlier examples.
    >
    let cindy: User = {email: 'cindy@example.com', admin: 'true'};
    cindy.admin;
    Result:
    type error: Type 'string' is not assignable to type 'boolean'.Pass Icon
  • The object type syntax looks similar to the literal object syntax. However, we can't use expressions like 1 + 1 or true || false in a type. That would be a syntax error because expressions are never allowed in types.

  • (Note that a syntax error is different from a type error!)

  • >
    type User = {email: string, admin: true || false};
    Result:
    syntax error: on line 1: ';' expected.Pass Icon
  • An object's properties can have any type. They can be simple types like strings, or complex types like other objects.

  • >
    type Reservation = {
    user: {
    email: string
    admin: boolean
    }
    roomNumber: number
    };
    let reservation: Reservation = {
    user: {
    email: 'betty@example.com',
    admin: true
    },
    roomNumber: 101,
    };
    reservation.user.email;
    Result:
    'betty@example.com'Pass Icon