TypeScript Object Types
An object type lists the properties an object must have and the type of each one. The compiler checks an object against that list.
An inline object type
The annotation lists two properties with their types. The object supplies both.
const person: { name: string; age: number } = { name: "Ada", age: 36 };
console.log(person.name);
console.log(person.age);A missing property is refused
The type lists age as well as name. The object leaves age out.
const person: { name: string; age: number } = { name: "Ada" };
console.log(person.name);An inline shape as a parameter type
A parameter can carry the same inline shape. The function reads the fields from it.
function describe(person: { name: string; age: number }): string {
return person.name + " is " + person.age + " years old";
}
console.log(describe({ name: "Ben", age: 24 }));Example
function area(rect: { width: number; height: number }): number {
return rect.width * rect.height;
}
const box: { width: number; height: number } = { width: 5, height: 4 };
console.log(area(box));Key points
- An object type lists each property name with its type inside braces.
- The properties in an object type are separated by semicolons.
- An object must supply every property its type lists.
- An object literal with a property the type does not list is also refused.
- The same inline shape can state the type of a variable or of a parameter.
In this example, the area parameter carries an inline object type with width and height. The box object supplies both properties as numbers. The function multiplies 5 by 4. The logged area is 20.
Note
The order of properties in an object does not need to match the order in its type.
Try it Yourself
Edit the code, then press Run.
Running is simulated ยท TypeScript Playground
Exercise
An object type lists name and age. What happens when an object supplies only name?