Execute Program

Everyday TypeScript: The Object Type

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

  • We've seen object types like {name: string, age: number}. But there's also a TypeScript type named simply object. If a function takes an object, TypeScript will let us pass any object type.

  • >
    function takesAnObject(obj: object): string {
    return 'it worked';
    }

    [
    takesAnObject({name: 'Amir'}),
    takesAnObject({count: 55}),
    ];
    Result:
    ['it worked', 'it worked']Pass Icon
  • Why bother with {name: string, age: number} when we can just say object? And why are we only mentioning the object type so late in this course?

  • The answer is simple: object is almost never useful. You may see it in older TypeScript code, and you may see it mentioned in some tutorials, so it's worth knowing that it exists. However, you'll probably never need to use it in new code.

  • The problem with object is that it doesn't know what properties the object has. Any attempt to access properties on an object is a type error.

  • >
    const user: object = {
    name: 'Amir',
    };

    user.name;
    Result:
    type error: Property 'name' does not exist on type 'object'.Pass Icon