TypeScript Object Types and Type Aliases
TypeScript object types describe the shape of an object: which properties it has and the type of each. A type alias gives that shape a reusable name with the type keyword.
Inline Object Types
function printUser(user: { name: string; age: number }) {
console.log(`${user.name} is ${user.age}`);
}
printUser({ name: "Bilal", age: 34 });
// printUser({ name: "Bilal" }); // Error: Property 'age' is missing.Bilal is 34
Type Aliases
Use type to name any type: an object shape, a union, a function signature. Names use PascalCase.
type Product = {
id: number;
name: string;
price: number;
};
const tea: Product = { id: 2, name: "Green Tea", price: 6 };
const list: Product[] = [tea, { id: 3, name: "Olive Oil", price: 18.75 }];
console.log(list.map((p) => p.price).reduce((a, b) => a + b));24.75
Optional and Readonly Properties
A ? after a property name makes it optional (its type includes undefined). readonly prevents reassignment after creation.
type Customer = {
readonly id: number;
name: string;
email?: string;
};
const c: Customer = { id: 1, name: "Alpha Traders" };
c.name = "Alpha Traders Ltd";
// c.id = 5; // Error: Cannot assign to 'id' because it is a read-only property.
console.log(c.name, c.email ?? "no email");Alpha Traders Ltd no email
Index Signatures and Record
When keys are not known in advance, use an index signature or the Record utility type.
type Stock = { [product: string]: number };
const stock: Stock = { rice: 120, tea: 300 };
stock.honey = 0;
const prices: Record<string, number> = { rice: 12.5 };
console.log(Object.keys(stock).length, prices.rice);3 12.5
Excess Property Checks
When you pass an object literal directly, TypeScript reports extra properties that the type does not declare. This catches typos in option objects.
type Options = { color: string; size?: number };
// const o: Options = { color: "red", szie: 2 };
// Error: Object literal may only specify known properties,
// and 'szie' does not exist in type 'Options'.
const o: Options = { color: "red", size: 2 };
console.log(o);{ color: 'red', size: 2 }Frequently asked questions
How do I make a property optional in TypeScript?
Add a question mark after its name: email?: string. The property may be missing or undefined.
What is a type alias in TypeScript?
A name for a type created with the type keyword, like type ID = string | number. It does not create a new type, just a reusable name.
What is the difference between Record and an index signature?
They are equivalent for string keys. Record<K, V> is shorter and also works with a union of literal keys, like Record<"a" | "b", number>.