TypeDI
Search…
Service Tokens
Service tokens are unique identifiers what provides type-safe access to a value stored in a Container.
1
import 'reflect-metadata';
2
import { Container, Token } from 'typedi';
3
4
export const JWT_SECRET_TOKEN = new Token<string>('MY_SECRET');
5
6
Container.set(JWT_SECRET_TOKEN, 'wow-such-secure-much-encryption');
7
8
/**
9
* Somewhere else in the application after the JWT_SECRET_TOKEN is
10
* imported in can be used to request the secret from the Container.
11
*
12
* This value is type-safe also because the Token is typed.
13
*/
14
const JWT_SECRET = Container.get(JWT_SECRET_TOKEN);
Copied!

Injecting service tokens

They can be used with the @Inject() decorator to overwrite the inferred type of the property or argument.
1
import 'reflect-metadata';
2
import { Container, Token, Inject, Service } from 'typedi';
3
4
export const JWT_SECRET_TOKEN = new Token<string>('MY_SECRET');
5
6
Container.set(JWT_SECRET_TOKEN, 'wow-such-secure-much-encryption');
7
8
@Service()
9
class Example {
10
@Inject(JWT_SECRET_TOKEN)
11
myProp: string;
12
}
13
14
const instance = Container.get(Example);
15
// 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.
Last modified 9d ago