Skip to content

Commit 482bd84

Browse files
authored
Fix setting default value for the TypeScript type (#117)
1 parent d57c326 commit 482bd84

File tree

2 files changed

+24
-6
lines changed

2 files changed

+24
-6
lines changed

index.d.ts

+6-6
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@ Return a default type if input type is nil.
1111
@template T - Input type.
1212
@template U - Default type.
1313
*/
14-
type WithDefault<T, U extends T> = T extends undefined | void | null ? U : T; // eslint-disable-line @typescript-eslint/ban-types
14+
type WithDefault<T, U> = T extends undefined | void | null ? U : T; // eslint-disable-line @typescript-eslint/ban-types
1515

1616
// TODO: Replace this with https://github.com/sindresorhus/type-fest/blob/main/source/includes.d.ts
1717
/**
@@ -237,9 +237,9 @@ export default function camelcaseKeys<
237237
options?: OptionsType
238238
): CamelCaseKeys<
239239
T,
240-
WithDefault<OptionsType['deep'], false>,
241-
WithDefault<OptionsType['pascalCase'], false>,
242-
WithDefault<OptionsType['preserveConsecutiveUppercase'], false>,
243-
WithDefault<OptionsType['exclude'], EmptyTuple>,
244-
WithDefault<OptionsType['stopPaths'], EmptyTuple>
240+
WithDefault<'deep' extends keyof OptionsType ? OptionsType['deep'] : undefined, false>,
241+
WithDefault<'pascalCase' extends keyof OptionsType ? OptionsType['pascalCase'] : undefined, false>,
242+
WithDefault<'preserveConsecutiveUppercase' extends keyof OptionsType ? OptionsType['preserveConsecutiveUppercase'] : undefined, false>,
243+
WithDefault<'exclude' extends keyof OptionsType ? OptionsType['exclude'] : undefined, EmptyTuple>,
244+
WithDefault<'stopPaths' extends keyof OptionsType ? OptionsType['stopPaths'] : undefined, EmptyTuple>
245245
>;

index.test-d.ts

+18
Original file line numberDiff line numberDiff line change
@@ -453,3 +453,21 @@ expectType<[
453453
}),
454454
]),
455455
);
456+
457+
// Test for function with inferred type
458+
// eslint-disable-next-line @typescript-eslint/comma-dangle
459+
function camelcaseKeysDeep<
460+
T extends Record<string, unknown> | readonly unknown[]
461+
>(response: T): CamelCaseKeys<T, true> {
462+
return camelcaseKeys(response, {deep: true});
463+
}
464+
465+
// eslint-disable-next-line @typescript-eslint/comma-dangle
466+
function camelcaseKeysPascalCase<
467+
T extends Record<string, unknown> | readonly unknown[]
468+
>(response: T): CamelCaseKeys<T, false, true> {
469+
return camelcaseKeys(response, {pascalCase: true});
470+
}
471+
472+
expectType<{fooBar: {hogeHoge: string}}>(camelcaseKeysDeep({foo_bar: {hoge_hoge: 'hoge_hoge'}}));
473+
expectType<{FooBar: string}>(camelcaseKeysPascalCase({foo_bar: 'foo_bar'}));

0 commit comments

Comments
 (0)