Skip to content

Commit

Permalink
feat: improve defaultFor response types
Browse files Browse the repository at this point in the history
  • Loading branch information
allohamora committed Sep 6, 2023
1 parent 4893b92 commit 7726b0f
Showing 1 changed file with 10 additions and 6 deletions.
16 changes: 10 additions & 6 deletions src/env/env.picker.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,12 @@ type MoveOptional<Type, Value> = Type extends null
export type BaseConfig = Record<string, string | undefined>;
export type EnvRecord<NodeEnv extends string, Value> = Partial<Record<NodeEnv | 'rest', Value>>;

export type DefaultForResponse<NodeEnv extends string, State, NewState, EnvOptions> = EnvOptions extends {
rest: NewState;
}
? EnvPicker<NodeEnv, NonNullable<State> | EnvOptions[keyof EnvOptions] | EnvOptions['rest']>
: EnvPicker<NodeEnv, State | NewState>;

export const wrapInEnvPickers = <NodeEnv extends string, Config extends BaseConfig>(
config: Config,
nodeEnv: NodeEnv,
Expand All @@ -31,14 +37,12 @@ export class EnvPicker<NodeEnv extends string, State> {
return this as EnvPicker<NodeEnv, NewState | NonNullable<State>>;
}

public defaultFor<NewState extends State, E extends EnvRecord<NodeEnv, NewState>>(
envRecord: E,
): E extends { rest: NewState } ? EnvPicker<NodeEnv, NewState> : EnvPicker<NodeEnv, NewState | undefined> {
public defaultFor<NewState extends State, EnvOptions extends EnvRecord<NodeEnv, NewState>>(
envRecord: EnvOptions,
): DefaultForResponse<NodeEnv, State, NewState, EnvOptions> {
this.state ??= (envRecord[this.nodeEnv] ?? envRecord.rest) as State;

return this as unknown as E extends { rest: NewState }
? EnvPicker<NodeEnv, NewState>
: EnvPicker<NodeEnv, NewState | undefined>;
return this as unknown as DefaultForResponse<NodeEnv, State, NewState, EnvOptions>;
}

public map<NewState>(mapper: (state: State) => NewState): EnvPicker<NodeEnv, NewState> {
Expand Down

0 comments on commit 7726b0f

Please sign in to comment.