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:
constpoet={born:1935,name:"Mary Oliver",};poet['born'];// Type: numberpoet.name;// Type: stringpoet.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 ...