Typing objects is just as simple as typing primitive values:
1
typeProfiler={
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
typeBook={
2
_id:string;
3
price:number;
4
category:number;
5
title:string;
6
description:string;
7
}
8
9
typePen={
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
typeProduct={
2
_id:string;
3
price:number;
4
category:number;
5
}
6
7
typeBook= Product &{
8
title:string;
9
description:string;
10
}
11
12
typePen= Product &{
13
brand:string;
14
type:string;
15
}
Copied!
Interfaces
Interfaces are another way of creating custom types.
1
interfaceIProduct{
2
_id:string;
3
price:number;
4
category:number;
5
}
6
7
interfaceIBookextendsIProduct{
8
title:string;
9
description:string;
10
}
11
12
interfaceIPenextendsIProduct{
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.