Skip to content
tsCheatSheet
GitHub

Object Types

Syntax for typing objects.

const vehicle: { maker: string; model: string; year: number } = {
	maker: 'Honda',
	model: 'Civic',
	year: 2008,
};

Infered Type

Type can be Infered.

const vehicle2 = {
	maker: 'Ford',
};
vehicle2.maker = 'Nissan'; // no error
vehicle2.maker = 2; // Error: Type 'number' is not assignable
// to type 'string'.

Optional Properties

Without optional properties.

const vehicle3: { maker: string; mileage: number } = {
	// Error: Property 'mileage' is missing in type
	// '{ type: string; }' but required in type
	// '{ maker: string; mileage: number; }'.
	maker: 'Honda',
};
vehicle3.mileage = 3000;

With optional properties.

const vehicle3: { maker: string; mileage?: number } = {
	// no error
	maker: 'Honda',
};
vehicle3.mileage = 3000;

Index Signatures

const nameAgeMap: { [index: string]: number } = {};
nameAgeMap.Matt = 25; // no error
nameAgeMap.Michael = 'Fifty'; // Error: Type 'string' is not
// assignable to type 'number'.