Skip to content

Commit 45dba81

Browse files
author
Hauke Broer
committed
add a example of type-safe token gone wrong and the benefit
1 parent 2bc3428 commit 45dba81

File tree

1 file changed

+21
-1
lines changed

1 file changed

+21
-1
lines changed

README.md

Lines changed: 21 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -237,7 +237,7 @@ export const TYPE = {
237237
> Since 1.0.0-beta.3 we use the symbol itself for indexing the dependencies.
238238
> Prior to this version we indexed the dependencies by the string of the symbol.
239239
240-
## Type-Safe Token (beta)
240+
## Type-Safe Token (2.0 beta)
241241
242242
With version 2 we added the possibility to use a type-safe way to identify our dependencies. This is done with tokens:
243243
@@ -248,6 +248,26 @@ export TYPE = {
248248
}
249249
```
250250
251+
In this case the type `MyServiceInterface` is inherited when using `container.get(TYPE.Service)`, `resolve(TYPE.Service)`
252+
and `wire(this, "service", TYPE.Service)`and does not need to be explicitly added. In case of the decorator `@inject(TYPE.Service)` it needs to be added
253+
but it throws a type error if the types don't match:
254+
255+
```ts
256+
class Example {
257+
@inject(TYPE.Service) // throws a type error because WrongInterface is not compatible with MyServiceInterface
258+
readonly service!: WrongInterface;
259+
}
260+
```
261+
262+
Correkt:
263+
264+
```ts
265+
class Example {
266+
@inject(TYPE.Service)
267+
readonly service!: MyServiceInterface;
268+
}
269+
```
270+
251271
## Usage
252272

253273
#### Step 1 - Installing the OWJA! IoC library

0 commit comments

Comments
 (0)