TypeDI
Search…
Inheritance
Inheritance is supported for properties when both the base and the extended class is marked with the @Service() decorator. Classes which extend a class with decorated properties will receive the initialized class instances on those properties upon creation.
1
import 'reflect-metadata';
2
import { Container, Token, Inject, Service } from 'typedi';
3
4
@Service()
5
class InjectedClass {
6
name: string = 'InjectedClass';
7
}
8
9
@Service()
10
class BaseClass {
11
name: string = 'BaseClass';
12
13
@Inject()
14
injectedClass: InjectedClass;
15
}
16
17
@Service()
18
class ExtendedClass extends BaseClass {
19
name: string = 'ExtendedClass';
20
}
21
22
const instance = Container.get(ExtendedClass);
23
// instance has the `name` property with "ExtendedClass" value (overwritten the base class)
24
// and the `injectedClass` property with the instance of the `InjectedClass` class
25
26
console.log(instance.injectedClass.name);
27
// logs "InjectedClass"
28
console.log(instance.name);
29
// logs "ExtendedClass"
Copied!
Last modified 9d ago
Copy link