HTML tutorial
CSS3 tutorial
Bootstrap tutorial
JavaScript tutorial
JQuery tutorial
AngularJS tutorial
React tutorial
NodeJS tutorial
PHP tutorial
Python tutorial
Python3 tutorial
Django tutorial
Linux tutorial
Docker tutorial
Ruby tutorial
Java tutorial
C tutorial
C ++ tutorial
Perl tutorial
JSP tutorial
Lua tutorial
Scala tutorial
Go tutorial
ASP.NET tutorial
C # tutorial
TypeScript has a specific syntax for typing objects
TypeScript can infer the types of properties based on their 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 properties that don't have to be defined 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;
Index signatures can be used for objects without a defined list of properties.
const nameAgeMap: { [index: string]: number } = {};
nameAgeMap.Jack = 25; // no error
nameAgeMap.Mark = "Fifty"; // Error: Type 'string' is not assignable to type 'number'.
Index signatures like this one can also be expressed with utility types like Record<string, number>
.
Learn more about utility types like this in our TypeScript Utility Types chapter.