// The instance.myProp property has the value assigned for the Token
Copied!
Tokens with same name
Two token with the same name are different tokens. The name is only used to help the developer identify the tokens during debugging and development. (It's included in error the messages.)
1
import 'reflect-metadata';
2
import { Container, Token } from 'typedi';
3
4
const tokenA = new Token('TOKEN');
5
const tokenB = new Token('TOKEN');
6
7
Container.set(tokenA, 'value-A');
8
Container.set(tokenB, 'value-B');
9
10
const tokenValueA = Container.get(tokenA);
11
// tokenValueA is "value-A"
12
const tokenValueB = Container.get(tokenB);
13
// tokenValueB is "value-B"
14
15
console.log(tokenValueA === tokenValueB);
16
// returns false, as Tokens are always unique
Copied!
Difference between Token and string identifier
They both achieve the same goal, however, it's recommended to use Tokens as they are type-safe and cannot be mistyped, while a mistyped string identifier will silently return undefined as value by default.