Typing objects
Typing objects is just as simple as typing primitive values:
1
type Profiler = {
2
logger?: string;
3
start: Date;
4
done(info?: string): boolean;
5
run: () => void;
6
}
Copied!
Properties of an object can be marked as optional with the ?.

Combining object types

Those types have common fields: _id, price, and category.
1
type Book = {
2
_id: string;
3
price: number;
4
category: number;
5
title: string;
6
description: string;
7
}
8
9
type Pen = {
10
_id: string;
11
price: number;
12
category: number;
13
brand: string;
14
type: string;
15
}
Copied!
Let's create a separate type for the common properties and rewrite the types:
1
type Product = {
2
_id: string;
3
price: number;
4
category: number;
5
}
6
7
type Book = Product & {
8
title: string;
9
description: string;
10
}
11
12
type Pen = Product & {
13
brand: string;
14
type: string;
15
}
Copied!

Interfaces

Interfaces are another way of creating custom types.
1
interface IProduct {
2
_id: string;
3
price: number;
4
category: number;
5
}
6
7
interface IBook extends IProduct {
8
title: string;
9
description: string;
10
}
11
12
interface IPen extends IProduct {
13
brand: string;
14
type: string;
15
}
Copied!
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