Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(as const): allow to declare tokens as const #27

Merged
merged 1 commit into from Aug 12, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
50 changes: 24 additions & 26 deletions README.md
Expand Up @@ -55,7 +55,7 @@ _Note: due to a [bug in TypeScript 3.8](https://github.com/microsoft/TypeScript/
An example:

```ts
import { rootInjector, tokens } from 'typed-inject';
import { rootInjector } from 'typed-inject';

interface Logger {
info(message: string): void;
Expand All @@ -69,12 +69,12 @@ const logger: Logger = {

class HttpClient {
constructor(private log: Logger) {}
public static inject = tokens('logger');
public static inject = ['logger'] as const;
}

class MyService {
constructor(private http: HttpClient, private log: Logger) {}
public static inject = tokens('httpClient', 'logger');
public static inject = ['httpClient', 'logger'] as const;
}

const appInjector = rootInjector.provideValue('logger', logger).provideClass('httpClient', HttpClient);
Expand All @@ -93,7 +93,7 @@ Dependencies are resolved using the static `inject` property on their classes. T
Expect compiler errors when you mess up the order of tokens or forget it completely.

```ts
import { rootInjector, tokens } from 'typed-inject';
import { rootInjector } from 'typed-inject';

// Same logger as before

Expand All @@ -104,7 +104,7 @@ class HttpClient {

class MyService {
constructor(private http: HttpClient, private log: Logger) {}
public static inject = tokens('logger', 'httpClient');
public static inject = ['logger', 'httpClient'] as const;
// ERROR! Types of parameters 'http' and 'args_0' are incompatible
}

Expand Down Expand Up @@ -152,16 +152,16 @@ The `Injector` interface is responsible for injecting classes or functions. Howe
In order to do anything useful with the `rootInjector`, you'll need to create child injectors. This what you do with the `provideXXX` methods.

```ts
import { rootInjector, tokens } from 'typed-inject';
import { rootInjector } from 'typed-inject';
function barFactory(foo: number) {
return foo + 1;
}
barFactory.inject = tokens('foo');
barFactory.inject = ['foo'] as const;
class Baz {
constructor(bar: number) {
console.log(`bar is: ${bar}`);
}
static inject = tokens('bar');
static inject = ['bar'] as const;
}

const childInjector = rootInjector
Expand All @@ -182,7 +182,7 @@ any ChildInjector _is stateful_. For example, it can [cache the injected value](
A common use case for dependency injection is the [decorator design pattern](https://en.wikipedia.org/wiki/Decorator_pattern). It is used to dynamically add functionality to existing dependencies. Typed inject supports decoration of existing dependencies using its `provideFactory` and `provideClass` methods.

```ts
import { tokens, rootInjector } from 'typed-inject';
import { rootInjector } from 'typed-inject';

class Foo {
public bar() {
Expand All @@ -199,7 +199,7 @@ function fooDecorator(foo: Foo) {
}
};
}
fooDecorator.inject = tokens('foo');
fooDecorator.inject = ['foo'] as const;

const fooProvider = rootInjector.provideClass('foo', Foo).provideFactory('foo', fooDecorator);
const foo = fooProvider.resolve('foo');
Expand Down Expand Up @@ -227,7 +227,7 @@ class Foo {
constructor(public log: Logger) {
log.info('Foo created');
}
static inject = tokens('log');
static inject = ['log'] as const;
}

const fooProvider = injector.provideFactory('log', loggerFactory, Scope.Transient).provideClass('foo', Foo, Scope.Singleton);
Expand Down Expand Up @@ -320,7 +320,7 @@ fooProvider.resolve('foo'); // => Error: Injector already disposed
Disposing of provided values is done in order of child first. So they are disposed in the opposite order of respective `providedXXX` calls (like a stack):

```ts
import { rootInjector, tokens } from 'typed-inject';
import { rootInjector} from 'typed-inject';

class Foo {
dispose() {
Expand All @@ -333,7 +333,7 @@ class Bar {
}
}
class Baz {
static inject = tokens('foo', 'bar');
static inject = ['foo', 'bar'] as const;
constructor(public foo: Foo, public bar: Bar) {}
}
rootInjector
Expand Down Expand Up @@ -361,11 +361,11 @@ Any `Injector` instance can always inject the following tokens:
An example:

```ts
import { rootInjector, Injector, tokens, TARGET_TOKEN, INJECTOR_TOKEN } from 'typed-inject';
import { rootInjector, Injector, TARGET_TOKEN, INJECTOR_TOKEN } from 'typed-inject';

class Foo {
constructor(injector: Injector<{}>, target: Function | undefined) {}
static inject = tokens(INJECTOR_TOKEN, TARGET_TOKEN);
static inject = [INJECTOR_TOKEN, TARGET_TOKEN] as const;
}

const foo = rootInjector.inject(Foo);
Expand All @@ -387,11 +387,11 @@ class GrandChild {
class Child {
public bar = 'foo';
constructor(public grandchild: GrandChild) {}
public static inject = tokens('grandChild');
public static inject = ['grandChild'] as const;
}
class Parent {
constructor(public readonly child: Child) {}
public static inject = tokens('child');
public static inject = ['child'] as const;
}
rootInjector
.provideClass('grandChild', GrandChild)
Expand Down Expand Up @@ -440,7 +440,7 @@ When there are any problems in the dependency graph, it gives a compiler error.
```ts
class Foo {
constructor(bar: number) {}
static inject = tokens('bar');
static inject = ['bar'] as const;
}
const foo /*: Foo*/ = injector.injectClass(Foo);
```
Expand All @@ -454,7 +454,7 @@ When there are any problems in the dependency graph, it gives a compiler error.
function foo(bar: number) {
return bar + 1;
}
foo.inject = tokens('bar');
foo.inject = ['bar'] as const;
const baz /*: number*/ = injector.injectFunction(Foo);
```

Expand All @@ -468,7 +468,7 @@ const foo = injector.resolve('foo');
function retrieveFoo(foo: number) {
return foo;
}
retrieveFoo.inject = tokens('foo');
retrieveFoo.inject = ['foo'] as const;
const foo2 = injector.injectFunction(retrieveFoo);
```

Expand All @@ -491,7 +491,7 @@ const fooInjector = injector.provideFactory('foo', () => 42);
function loggerFactory(target: Function | undefined) {
return new Logger((target && target.name) || '');
}
loggerFactory.inject = tokens(TARGET_TOKEN);
loggerFactory.inject = [TARGET_TOKEN] as const;
const fooBarInjector = fooInjector.provideFactory('logger', loggerFactory, Scope.Transient);
```

Expand Down Expand Up @@ -519,16 +519,14 @@ The `Scope` enum indicates the scope of a provided injectable (class or factory)

### `tokens`

The `tokens` function is a simple helper method that makes sure that an `inject` array is filled with a [tuple type filled with literal strings](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-0.html#rest-parameters-with-tuple-types).
The `tokens` function is a simple helper method that makes sure that an `inject` array is filled with a [readonly tuple type filled with literal strings](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-0.html#rest-parameters-with-tuple-types). It is mostly there for backward compatibility reasons, since we can now use `as const`, but one might also simply prefer to use `tokens` instead.

```ts
const inject = tokens('foo', 'bar');
// Equivalent to:
const inject: ['foo', 'bar'] = ['foo', 'bar'].
const inject = ['foo', 'bar'] as const;
```

_Note: hopefully [TypeScript will introduce explicit tuple syntax](https://github.com/Microsoft/TypeScript/issues/16656), so this helper method can be removed_

### `InjectableClass<TContext, R, Tokens extends InjectionToken<TContext>[]>`

The `InjectableClass` interface is used to identify the (static) interface of classes that can be injected. It is defined as follows:
Expand Down Expand Up @@ -575,7 +573,7 @@ class Boom {
}
class Prison {
constructor(public readonly child: Boom) {}
public static inject = tokens('boom');
public static inject = ['boom'] as const;
}
try {
rootInjector.provideClass('boom', Boom).injectClass(Prison);
Expand Down
2 changes: 1 addition & 1 deletion src/api/CorrespondingType.ts
Expand Up @@ -9,6 +9,6 @@ export type CorrespondingType<TContext, T extends InjectionToken<TContext>> = T
? TContext[T]
: never;

export type CorrespondingTypes<TContext, TS extends InjectionToken<TContext>[]> = {
export type CorrespondingTypes<TContext, TS extends readonly InjectionToken<TContext>[]> = {
[K in keyof TS]: TS[K] extends InjectionToken<TContext> ? CorrespondingType<TContext, TS[K]> : never;
};
10 changes: 5 additions & 5 deletions src/api/Injectable.ts
@@ -1,28 +1,28 @@
import { CorrespondingTypes } from './CorrespondingType';
import { InjectionToken } from './InjectionToken';

export type InjectableClass<TContext, R, Tokens extends InjectionToken<TContext>[]> =
export type InjectableClass<TContext, R, Tokens extends readonly InjectionToken<TContext>[]> =
| ClassWithInjections<TContext, R, Tokens>
| ClassWithoutInjections<R>;

export interface ClassWithInjections<TContext, R, Tokens extends InjectionToken<TContext>[]> {
export interface ClassWithInjections<TContext, R, Tokens extends readonly InjectionToken<TContext>[]> {
new (...args: CorrespondingTypes<TContext, Tokens>): R;
readonly inject: Tokens;
}

export type ClassWithoutInjections<R> = new () => R;

export type InjectableFunction<TContext, R, Tokens extends InjectionToken<TContext>[]> =
export type InjectableFunction<TContext, R, Tokens extends readonly InjectionToken<TContext>[]> =
| InjectableFunctionWithInject<TContext, R, Tokens>
| InjectableFunctionWithoutInject<R>;

export interface InjectableFunctionWithInject<TContext, R, Tokens extends InjectionToken<TContext>[]> {
export interface InjectableFunctionWithInject<TContext, R, Tokens extends readonly InjectionToken<TContext>[]> {
(...args: CorrespondingTypes<TContext, Tokens>): R;
readonly inject: Tokens;
}

export type InjectableFunctionWithoutInject<R> = () => R;

export type Injectable<TContext, R, Tokens extends InjectionToken<TContext>[]> =
export type Injectable<TContext, R, Tokens extends readonly InjectionToken<TContext>[]> =
| InjectableClass<TContext, R, Tokens>
| InjectableFunction<TContext, R, Tokens>;
8 changes: 4 additions & 4 deletions src/api/Injector.ts
Expand Up @@ -4,16 +4,16 @@ import { Scope } from './Scope';
import { TChildContext } from './TChildContext';

export interface Injector<TContext = {}> {
injectClass<R, Tokens extends InjectionToken<TContext>[]>(Class: InjectableClass<TContext, R, Tokens>): R;
injectFunction<R, Tokens extends InjectionToken<TContext>[]>(Class: InjectableFunction<TContext, R, Tokens>): R;
injectClass<R, Tokens extends readonly InjectionToken<TContext>[]>(Class: InjectableClass<TContext, R, Tokens>): R;
injectFunction<R, Tokens extends readonly InjectionToken<TContext>[]>(Class: InjectableFunction<TContext, R, Tokens>): R;
resolve<Token extends keyof TContext>(token: Token): TContext[Token];
provideValue<Token extends string, R>(token: Token, value: R): Injector<TChildContext<TContext, R, Token>>;
provideClass<Token extends string, R, Tokens extends InjectionToken<TContext>[]>(
provideClass<Token extends string, R, Tokens extends readonly InjectionToken<TContext>[]>(
token: Token,
Class: InjectableClass<TContext, R, Tokens>,
scope?: Scope
): Injector<TChildContext<TContext, R, Token>>;
provideFactory<Token extends string, R, Tokens extends InjectionToken<TContext>[]>(
provideFactory<Token extends string, R, Tokens extends readonly InjectionToken<TContext>[]>(
token: Token,
factory: InjectableFunction<TContext, R, Tokens>,
scope?: Scope
Expand Down
2 changes: 1 addition & 1 deletion src/tokens.ts
Expand Up @@ -7,6 +7,6 @@
* ```
* @param tokens The tokens as args
*/
export function tokens<TS extends string[]>(...tokens: TS): TS {
export function tokens<TS extends readonly string[]>(...tokens: TS): TS {
return tokens;
}
20 changes: 20 additions & 0 deletions testResources/dependency-graph-as-const.ts
@@ -0,0 +1,20 @@
// error: false
import { rootInjector } from '../src/index';

class Baz {
public baz = 'baz';
}

function bar(baz: Baz) {
return { baz };
}
bar.inject = ['baz'] as const;

class Foo {
constructor(public bar: { baz: Baz }, public baz: Baz, public qux: boolean) {}
public static inject = ['bar', 'baz', 'qux'] as const;
}

const fooInjector = rootInjector.provideValue('qux', true).provideClass('baz', Baz).provideFactory('bar', bar);

const foo: Foo = fooInjector.injectClass(Foo);
10 changes: 9 additions & 1 deletion testResources/tokens-of-type-string.ts
@@ -1 +1,9 @@
// error: "Type 'string[]' is not assignable to type 'InjectionToken<TChildContext<{}, number, \"bar\">>[]'"import { rootInjector } from '../src/index';class Foo { constructor(bar: number) {} public static inject = ['bar'];}const foo: Foo = rootInjector.provideValue('bar', 42).injectClass(Foo);
// error: "Type 'string[]' is not assignable to type 'readonly InjectionToken<TChildContext<{}, number, \"bar\">>[]'"

import { rootInjector } from '../src/index';

class Foo {
constructor(bar: number) {}
public static inject = ['bar'];
}
const foo: Foo = rootInjector.provideValue('bar', 42).injectClass(Foo);
9 changes: 8 additions & 1 deletion testResources/unknown-token.ts
@@ -1 +1,8 @@
// error: "Type '[\"not-exists\"]' is not assignable to type 'InjectionToken<{}>[]"import { rootInjector, tokens } from '../src/index';function foo(bar: string) {}foo.inject = tokens('not-exists');rootInjector.injectFunction(foo);
// error: "Type '[\"not-exists\"]' is not assignable to type 'readonly InjectionToken<{}>[]"

import { rootInjector, tokens } from '../src/index';

function foo(bar: string) {}
foo.inject = tokens('not-exists');

rootInjector.injectFunction(foo);