Skip to content

Commit

Permalink
Fix the .get() TypeScript return type (#117)
Browse files Browse the repository at this point in the history
Co-authored-by: Sindre Sorhus <sindresorhus@gmail.com>
  • Loading branch information
SnosMe and sindresorhus committed Aug 13, 2020
1 parent 1dcfd0d commit 526002e
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 7 deletions.
9 changes: 6 additions & 3 deletions source/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -165,9 +165,12 @@ class Conf<T extends Record<string, any> = Record<string, unknown>> implements I
@param key - The key of the item to get.
@param defaultValue - The default value if the item does not exist.
*/
get<Key extends keyof T>(key: Key | string): T[Key] | undefined;
get<Key extends keyof T, Default = T[Key]>(key: Key | string, defaultValue: Default): T[Key] | Default;
get<Key extends keyof T, Default = T[Key]>(key: Key | string, defaultValue?: Default): Default | undefined {
get<Key extends keyof T>(key: Key): T[Key];
get<Key extends keyof T>(key: Key, defaultValue: Required<T>[Key]): Required<T>[Key];
// This overload is used for dot-notation access.
// We exclude `keyof T` as an incorrect type for the default value should not fall through to this overload.
get<Key extends string, Value = unknown>(key: Exclude<Key, keyof T>, defaultValue?: Value): Value;
get(key: string, defaultValue?: unknown): unknown {
if (this.#options.accessPropertiesByDotNotation) {
return this._get(key, defaultValue);
}
Expand Down
10 changes: 6 additions & 4 deletions test/index.test-d.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/* eslint-disable no-new */
import {expectType, expectAssignable} from 'tsd';
import {expectType, expectAssignable, expectError} from 'tsd';
import Conf from '../source';

type UnicornFoo = {
Expand Down Expand Up @@ -67,7 +67,7 @@ conf.set({
}
});

expectType<string | undefined>(conf.get('foo'));
expectType<string>(conf.get('foo'));
expectType<string>(conf.get('foo', 'bar'));
conf.delete('foo');
expectType<boolean>(conf.has('foo'));
Expand Down Expand Up @@ -122,11 +122,13 @@ console.log(config.get('unicorn'));
//=> undefined

// Should be stored type or default
expectType<boolean | undefined>(config.get('isRainbow'));
expectType<boolean>(config.get('isRainbow'));
expectType<boolean>(config.get('isRainbow', false));

expectType<string | undefined>(config.get('unicorn'));
expectType<string | undefined | number>(config.get('unicorn', 1));
expectType<string>(config.get('unicorn', 'rainbow'));
// @ts-expect-error
expectError<number>(config.get('unicorn', 1));

// --

Expand Down

0 comments on commit 526002e

Please sign in to comment.