Execute Program

TypeScript Basics: Anonymous Object Types

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

  • Sometimes, it's not worth naming an object type. In those cases, we can put the type directly in a function's signature.

  • >
    function extractEmail(user: {email: string}): string {
    return user.email;
    }
    extractEmail({email: 'amir@example.com'});
    Result:
    'amir@example.com'Pass Icon
  • In that code, the type {email: string} is an "anonymous object type" because we didn't give it a name.

  • We can use JavaScript's destructuring along with this. The destructuring is done with the usual JavaScript syntax. The type is defined with the usual TypeScript syntax.

  • Here's an example of a function that takes an object with a name property and returns its name, without destructuring.

  • >
    function userName(user: {name: string}): string {
    return user.name;
    }
    userName({name: 'Amir'});
    Result:
    'Amir'Pass Icon
  • Now, let's shorten this by using JavaScript destructuring, which "grabs" name out of the argument. Destructuring and object arguments sometimes look strange together, but remember that the type is to the right of the : symbol.

  • >
    function userName({name}: {name: string}): string {
    return name;
    }
    userName({name: 'Amir'});
    Result:
    'Amir'Pass Icon