TypeScript provides a specific syntax for defining the types of objects.
const car: { type: string, model: string, year: number } = { type: “Toyota”, model: “Corolla”, year: 2009 }; |
TypeScript can infer property types based on their assigned values.
const car = { type: “Toyota”, }; car.type = “Ford”; // no error car.type = 2; // Error: Type ‘number’ is not assignable to type ‘string’. |
Optional properties are those that do not need to be included in the object definition.
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; |
const car: { type: string, mileage?: number } = { // no error type: “Toyota” }; car.mileage = 2000; |
Optional properties are those that do not need to be included in the object definition.
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>. |