Besides primitives, most values are objects: values with properties. In TypeScript you describe that shape inline or with a named type.
Inline object types
List the properties and their types:
function printCoord(pt: { x: number; y: number }) {
console.log("The coordinate's x value is " + pt.x);
console.log("The coordinate's y value is " + pt.y);
}
printCoord({ x: 3, y: 7 });
You can separate properties with , or ;. The trailing separator is optional. If you omit a property's type, it defaults to any.
Optional properties
Add ? after a property name to make it optional:
function printName(obj: { first: string; last?: string }) {
// ...
}
printName({ first: "Bob" });
printName({ first: "Alice", last: "Alisson" });
Reading an optional property may give undefined. Check before use:
function printName(obj: { first: string; last?: string }) {
// Error without a check: 'obj.last' is possibly 'undefined'.
// console.log(obj.last.toUpperCase());
if (obj.last !== undefined) {
console.log(obj.last.toUpperCase());
}
// Or optional chaining:
console.log(obj.last?.toUpperCase());
}
Nested shapes
Object types nest naturally:
function printUser(user: {
id: number;
profile: {
name: string;
email?: string;
};
}) {
console.log(user.profile.name);
console.log(user.profile.email?.toLowerCase());
}
For reuse, prefer a type alias or interface (next lessons) instead of copying the same inline shape everywhere.
Excess property checks
When you pass an object literal directly, TypeScript is strict about unknown keys:
function printCoord(pt: { x: number; y: number }) {
console.log(pt.x, pt.y);
}
printCoord({ x: 1, y: 2, z: 3 });
// Error: Object literal may only specify known properties, and 'z' does not exist...
That catches typos like widht instead of width when calling APIs.
Practice
function describe(product: {
name: string;
price: number;
inStock?: boolean;
}) {
const stock = product.inStock ? "in stock" : "status unknown";
console.log(`${product.name}: $${product.price} (${stock})`);
}
- Call
describewith and withoutinStock. - Try adding a typo property on the object literal and fix it.
- Safely log
inStockonly when it is defined. - Later, rename this shape with a
typealias orinterfaceonce you learn those.