Curriculum
Course: TypeScript
Login
Text lesson

TS Object Types

TypeScript provides a specific syntax for defining the types of objects.

Example

const car: { type: string, model: string, year: number } = {
  type: “Toyota”,
  model: “Corolla”,
  year: 2009
};

Type Inference

TypeScript can infer property types based on their assigned values.

Example

const car = {
  type: “Toyota”,
};
car.type = “Ford”// no error
car.type = 2// Error: Type ‘number’ is not assignable to type ‘string’.

Optional Properties

Optional properties are those that do not need to be included in the object definition.

Example without an optional property

const car: { type: string, mileage: number } = { // Error: Property ‘mileage’ is missing in type ‘{ type: string; }’ but required in type ‘{ type: string; mileage: number; }’.
  type: “Toyota”,
};
car.mileage = 2000;

Example with an optional property

const car: { type: string, mileage?: number } = { // no error
  type: “Toyota”
};
car.mileage = 2000;

Index Signatures

Optional properties are those that do not need to be included in the object definition.

Example

const nameAgeMap: { [index: string]: number } = {};
nameAgeMap.Jack = 25// no error
nameAgeMap.Mark = “Fifty”// Error: Type ‘string’ is not assignable to type ‘number’.

Index signatures can also be represented using utility types, such as Record<string, number>.