Skip to Content
Learning TypeScript
book

Learning TypeScript

by Josh Goldberg
June 2022
Beginner
320 pages
6h 40m
English
O'Reilly Media, Inc.
Book available
Content preview from Learning TypeScript

Chapter 4. Objects

Object literals

A set of keys and values

Each with their own type

Chapter 3, “Unions and Literals” fleshed out union and literal types: working with primitives such as boolean and literal values of them such as true. Those primitives only scratch the surface of the complex object shapes JavaScript code commonly uses. TypeScript would be pretty unusable if it weren’t able to represent those objects. This chapter will cover how to describe complex object shapes and how TypeScript checks their assignability.

Object Types

When you create an object literal with {...} syntax, TypeScript will consider it to be a new object type, or type shape, based on its properties. That object type will have the same property names and primitive types as the object’s values. Accessing properties of the value can be done with either value.member or the equivalent value['member'] syntax.

TypeScript understands that the following poet variable’s type is that of an object with two properties: born, of type number, and name, of type string. Accessing those members would be allowed, but attempting to access any other member name would cause a type error for that name not existing:

const poet = {
    born: 1935,
    name: "Mary Oliver",
};

poet['born']; // Type: number
poet.name; // Type: string

poet.end;
//   ~~~
// Error: Property 'end' does not exist on
// type '{ born: number; name: string; }'.

Object types are a core concept for how TypeScript understands JavaScript code. Every value other ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Understanding TypeScript

Understanding TypeScript

Maximilian Schwarzmüller

Publisher Resources

ISBN: 9781098110321Errata PageSupplemental Content