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.somePropertywill returnundefinedifsomePropertydoesn'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 domyObject.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: stringadmin: boolean};let amir: User = {email: 'amir@example.com',admin: true,};amir.admin;Result:
true
Object types require that all properties are present. (You can write
type errorif 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'. 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:
true
- 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'.
The object type syntax looks similar to the literal object syntax. However, we can't use expressions like
1 + 1ortrue || falsein 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.
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: stringadmin: boolean}roomNumber: number};let reservation: Reservation = {user: {email: 'betty@example.com',admin: true},roomNumber: 101,};reservation.user.email;Result:
'betty@example.com'