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 simplyobject. If a function takes anobject, 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']
Why bother with
{name: string, age: number}when we can just sayobject? And why are we only mentioning theobjecttype so late in this course?The answer is simple:
objectis 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
objectis that it doesn't know what properties the object has. Any attempt to access properties on anobjectis a type error.>
const user: object = {name: 'Amir',};user.name;Result:
type error: Property 'name' does not exist on type 'object'.