Skip to content

Commit

Permalink
feat(@nestjs/config): better generic support for registerAs
Browse files Browse the repository at this point in the history
Add support to specify the return type of a config factory.

BREAKING CHANGE:

The commit will break the code which already utilizing the generic of
`registerAs` function.
  • Loading branch information
JasonHK committed Apr 11, 2020
1 parent 0fb4bd7 commit 75947a1
Show file tree
Hide file tree
Showing 4 changed files with 13 additions and 10 deletions.
10 changes: 5 additions & 5 deletions lib/interfaces/config-factory.interface.ts
@@ -1,7 +1,7 @@
type ConfigFactoryReturnValue =
| Record<string, any>
| Promise<Record<string, any>>;
import { ConfigObject } from '../types';

type ConfigFactoryReturnValue<T extends ConfigObject> = T | Promise<T>;

export type ConfigFactory<
T extends ConfigFactoryReturnValue = ConfigFactoryReturnValue
> = () => T;
T extends ConfigObject = ConfigObject
> = () => ConfigFactoryReturnValue<T>;
1 change: 1 addition & 0 deletions lib/types/config-object.type.ts
@@ -0,0 +1 @@
export type ConfigObject = Record<string, any>;
1 change: 1 addition & 0 deletions lib/types/index.ts
@@ -1 +1,2 @@
export * from './config.type';
export * from './config-object.type';
11 changes: 6 additions & 5 deletions lib/utils/register-as.util.ts
Expand Up @@ -3,17 +3,18 @@ import {
PARTIAL_CONFIGURATION_PROPNAME,
} from '../config.constants';
import { ConfigFactory } from '../interfaces';
import { ConfigObject } from '../types';
import { getConfigToken } from './get-config-token.util';

export type ConfigFactoryKeyHost = { KEY: string };

/**
* Registers the configuration object behind a specified token.
*/
export function registerAs<T extends ConfigFactory = ConfigFactory>(
token: string,
configFactory: T,
): T & ConfigFactoryKeyHost {
export function registerAs<
TConfig extends ConfigObject,
TFactory extends ConfigFactory = ConfigFactory<TConfig>
>(token: string, configFactory: TFactory): TFactory & ConfigFactoryKeyHost {
Object.defineProperty(configFactory, PARTIAL_CONFIGURATION_KEY, {
configurable: false,
enumerable: false,
Expand All @@ -27,5 +28,5 @@ export function registerAs<T extends ConfigFactory = ConfigFactory>(
writable: false,
});

return configFactory as T & ConfigFactoryKeyHost;
return configFactory as TFactory & ConfigFactoryKeyHost;
}

0 comments on commit 75947a1

Please sign in to comment.