Skip to content

Commit

Permalink
Fix setting default value for the TypeScript type (#117)
Browse files Browse the repository at this point in the history
  • Loading branch information
yutak23 committed Oct 17, 2023
1 parent d57c326 commit 482bd84
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 6 deletions.
12 changes: 6 additions & 6 deletions index.d.ts
Expand Up @@ -11,7 +11,7 @@ Return a default type if input type is nil.
@template T - Input type.
@template U - Default type.
*/
type WithDefault<T, U extends T> = T extends undefined | void | null ? U : T; // eslint-disable-line @typescript-eslint/ban-types
type WithDefault<T, U> = T extends undefined | void | null ? U : T; // eslint-disable-line @typescript-eslint/ban-types

// TODO: Replace this with https://github.com/sindresorhus/type-fest/blob/main/source/includes.d.ts
/**
Expand Down Expand Up @@ -237,9 +237,9 @@ export default function camelcaseKeys<
options?: OptionsType
): CamelCaseKeys<
T,
WithDefault<OptionsType['deep'], false>,
WithDefault<OptionsType['pascalCase'], false>,
WithDefault<OptionsType['preserveConsecutiveUppercase'], false>,
WithDefault<OptionsType['exclude'], EmptyTuple>,
WithDefault<OptionsType['stopPaths'], EmptyTuple>
WithDefault<'deep' extends keyof OptionsType ? OptionsType['deep'] : undefined, false>,
WithDefault<'pascalCase' extends keyof OptionsType ? OptionsType['pascalCase'] : undefined, false>,
WithDefault<'preserveConsecutiveUppercase' extends keyof OptionsType ? OptionsType['preserveConsecutiveUppercase'] : undefined, false>,
WithDefault<'exclude' extends keyof OptionsType ? OptionsType['exclude'] : undefined, EmptyTuple>,
WithDefault<'stopPaths' extends keyof OptionsType ? OptionsType['stopPaths'] : undefined, EmptyTuple>
>;
18 changes: 18 additions & 0 deletions index.test-d.ts
Expand Up @@ -453,3 +453,21 @@ expectType<[
}),
]),
);

// Test for function with inferred type
// eslint-disable-next-line @typescript-eslint/comma-dangle
function camelcaseKeysDeep<
T extends Record<string, unknown> | readonly unknown[]
>(response: T): CamelCaseKeys<T, true> {
return camelcaseKeys(response, {deep: true});
}

// eslint-disable-next-line @typescript-eslint/comma-dangle
function camelcaseKeysPascalCase<
T extends Record<string, unknown> | readonly unknown[]
>(response: T): CamelCaseKeys<T, false, true> {
return camelcaseKeys(response, {pascalCase: true});
}

expectType<{fooBar: {hogeHoge: string}}>(camelcaseKeysDeep({foo_bar: {hoge_hoge: 'hoge_hoge'}}));
expectType<{FooBar: string}>(camelcaseKeysPascalCase({foo_bar: 'foo_bar'}));

0 comments on commit 482bd84

Please sign in to comment.