TypeScript Tutorial · TypeScript Basics · Lesson 4 of 25
TypeScript Object Types and Type Aliases
Describe object shapes, optional and readonly properties, and name types with type.
Object types
Describe the properties an object must have:
function describe(user: { name: string; age: number }): string {
return `${user.name} is ${user.age}`;
}
console.log(describe({ name: "Ada", age: 36 }));
Output
Ada is 36
Optional and readonly properties
prop?: type— the property may be missing (its type includesundefined).readonly prop: type— can't be reassigned after creation.
Type aliases
type Name = ... gives any type a reusable name:
type Product = {
readonly id: number;
name: string;
price: number;
description?: string;
};
const mug: Product = { id: 1, name: "Mug", price: 9.5 };
mug.price = 8.5;
// @ts-expect-error — Cannot assign to 'id' because it is a read-only property.
mug.id = 2; // types are compile-time only: if you ignore the error, the assignment still runs
console.log(mug, mug.description ?? "(no description)");
Output
{ id: 2, name: 'Mug', price: 8.5 } (no description)Excess property checks
Object literals with unknown properties are rejected — this catches typos like emial:
type Contact = { name: string; email: string };
// @ts-expect-error — Object literal may only specify known properties, and 'emial' does not exist.
const c: Contact = { name: "Ada", emial: "[email protected]" };
console.log(c);
Output
{ name: 'Ada', emial: '[email protected]' }Test yourself
How do you mark an object property as optional?
name: string?name?: stringoptional name: stringname: string | optional
Show answer
Answer: name?: string