Typing objects
Typing objects is just as simple as typing primitive values:
type Profiler = {
logger?: string;
start: Date;
done(info?: string): boolean;
run: () => void;
}Properties of an object can be marked as optional with the ?.
Combining object types
Those types have common fields: _id, price, and category.
type Book = {
_id: string;
price: number;
category: number;
title: string;
description: string;
}
type Pen = {
_id: string;
price: number;
category: number;
brand: string;
type: string;
}Let's create a separate type for the common properties and rewrite the types:
Interfaces
Interfaces are another way of creating custom types.
There are some very minor differences between type aliases and interfaces. In general interfaces seem to be more suitable for object-oriented code with classes.
Resources
Last updated
Was this helpful?