Skip to content

Commit

Permalink
feat: improve defaultFor with rest return value
Browse files Browse the repository at this point in the history
  • Loading branch information
allohamora committed Jul 27, 2023
1 parent 2d57b5d commit 304530d
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 4 deletions.
5 changes: 4 additions & 1 deletion __tests__/unit/env.picker.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,14 +40,17 @@ describe('EnvPicker', () => {
).toBe(undefined);

expect(new EnvPicker(false as boolean | undefined, 'test').defaultFor({ test: true }).value()).toBe(false);
expect(new EnvPicker('', 'test').defaultFor({ test: '123' }).value()).toBe('');
expect(new EnvPicker('' as string | undefined, 'test').defaultFor({ test: '123' }).value()).toBe('');
});
});

describe('map', () => {
it('maps state', () => {
expect(new EnvPicker('123', 'test').map(Number).value()).toBe(123);
expect(new EnvPicker(undefined as string | undefined, 'test').default('123').map(Number).value()).toBe(123);
expect(
new EnvPicker(undefined as string | undefined, 'test').defaultFor({ rest: '123' }).map(Number).value(),
).toBe(123);
expect(new EnvPicker('false', 'test').default('123').map(JSON.parse).value()).toBe(false);
expect(new EnvPicker(undefined as string | undefined, 'test').map((state) => !!state).value()).toBe(false);
});
Expand Down
8 changes: 5 additions & 3 deletions src/env/env.picker.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,10 +31,12 @@ export class EnvPicker<NodeEnv extends string, State> {
return this as unknown as EnvPicker<NodeEnv, NewState | NonNullable<State>>;
}

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

return this;
return this as unknown as EnvOptions extends { rest: NewState }
? EnvPicker<NodeEnv, NonNullable<NewState>>
: EnvPicker<NodeEnv, NewState>;
}

public map<Result>(mapper: (state: State) => Result) {
Expand Down

0 comments on commit 304530d

Please sign in to comment.