Execute Program

Everyday TypeScript: The Empty Object Type

Welcome to the The Empty Object Type lesson!

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

  • TypeScript allows object types with no properties at all, written as {}. Because of TypeScript's structural typing, we can still pass non-empty objects to a {}.

  • Remember that "structural typing" for objects means "type A is compatible with B if A has all of the properties of B". If B is the empty type, {}, then every type except null and undefined is compatible with it. The {} type has no properties, so there's nothing to be incompatible with!

  • >
    function takesAlmostAnything(obj: {}) {
    return 'it worked';
    }

    [
    takesAlmostAnything({name: 'Amir'}),
    takesAlmostAnything({loginCount: 55}),
    takesAlmostAnything(55),
    ];
    Result:
    ['it worked', 'it worked', 'it worked']Pass Icon
  • >
    function takesAlmostAnything(obj: {}) {
    return 'it worked';
    }

    takesAlmostAnything(null);
    Result:
    type error: Argument of type 'null' is not assignable to parameter of type '{}'.Pass Icon
  • You'll probably never write a function that takes an argument of type {}. However, {} can be useful with generic types.

  • For example, the React web user interface library lets us write "components" that render elements on the page, like buttons or user profiles. React components are functions that take an object used to customize the component. That object is called "props" in React, short for "properties".

  • A Button component might take {backgroundColor: string} props to let us specify the color. A UserProfile component might take {user: User} props. It renders the user's various properties (their name, their avatar image, etc.) as part of the page.

  • We can define a generic type for a heavily simplified version of React components:

  • >
    type Component<P> = (props: P) => string;
  • (We've named our type parameter <P> for "props", rather than the usual <T>. As with most things in programming, we can use any name we like.)

  • Some components don't need any props. For example, a company's landing page will have many components that contain marketing copy and images. They always render the same static content, so they don't need any props. For components without props, we'll specify a generic type parameter of {}.

  • Note: this code example reuses elements (variables, etc.) defined in earlier examples.
    >
    const MarketingCopy: Component<{}> = () => {
    return 'The perfect product!';
    };

    MarketingCopy({});
    Result:
    'The perfect product!'Pass Icon
  • In the example above, we could also write Component<object>, which type checks and works. However, Component<{}> communicates our intent more clearly: this component takes no props at all.