Careeroza
Object Types
Describing an Object
An object type lists each property and its type, separated by ; or ,.
Example
const product: { id: number; name: string; price: number } = {
id: 1,
name: "Running Shoes",
price: 2999,
};
function printProduct(p: { name: string; price: number }): void {
console.log(`${p.name} - Rs. ${p.price}`);
}
printProduct(product);
printProduct({ name: "Water Bottle", price: 349 });Output
Running Shoes - Rs. 2999 Water Bottle - Rs. 349
Missing and Extra Properties
Example
A missing property is TS2741. An unknown extra property in an object literal is caught by the excess property check (TS2353, or TS2561 with a "did you mean" hint), which catches typos like prise.
const a: { name: string; price: number } = { name: "Pen" };
const b: { name: string; price: number } = { name: "Pen", price: 20, prise: 20 };Compiler output (tsc)
Line 1: error TS2741: Property 'price' is missing in type '{ name: string; }' but required in type '{ name: string; price: number; }'.
Line 2: error TS2561: Object literal may only specify known properties, but 'prise' does not exist in type '{ name: string; price: number; }'. Did you mean to write 'price'?Nested Objects
Example
const user: {
name: string;
address: { city: string; pincode: string };
} = {
name: "Sneha",
address: { city: "Bengaluru", pincode: "560001" },
};
console.log(user.address.city, user.address.pincode);Output
Bengaluru 560001