Skip to content

Commit

Permalink
Improve type inference.
Browse files Browse the repository at this point in the history
Type inferences for some kind of values(functions, records, promises,.etc) are not correct when deep option is enabled. It is because CamelCaseKeys type accepts Record<string, any> and then accepts some object-like types such as functions or promises.
  • Loading branch information
Masa-Shin committed Jun 21, 2022
1 parent e783aeb commit 71087d6
Show file tree
Hide file tree
Showing 2 changed files with 45 additions and 17 deletions.
38 changes: 21 additions & 17 deletions index.d.ts
Expand Up @@ -45,13 +45,15 @@ export type CamelCaseKeys<
> = T extends readonly any[]
// Handle arrays or tuples.
? {
[P in keyof T]: CamelCaseKeys<
T[P],
Deep,
IsPascalCase,
Exclude,
StopPaths
>;
[P in keyof T]: Record<string, unknown> extends CamelCaseKeys<T[P]>
? T[P]
: CamelCaseKeys<
T[P],
Deep,
IsPascalCase,
Exclude,
StopPaths
>;
}
: T extends Record<string, any>
// Handle objects.
Expand All @@ -64,16 +66,18 @@ export type CamelCaseKeys<
true,
]
? T[P]
: [Deep] extends [true]
? CamelCaseKeys<
T[P],
Deep,
IsPascalCase,
Exclude,
StopPaths,
AppendPath<Path, P & string>
>
: T[P];
: Record<string, unknown> extends CamelCaseKeys<T[P]>
? T[P]
: [Deep] extends [true]
? CamelCaseKeys<
T[P],
Deep,
IsPascalCase,
Exclude,
StopPaths,
AppendPath<Path, P & string>
>
: T[P];
}
// Return anything else as-is.
: T;
Expand Down
24 changes: 24 additions & 0 deletions index.test-d.ts
Expand Up @@ -350,3 +350,27 @@ expectNotType<InvalidConvertedExcludeObjectDataType>(
exclude,
}),
);

expectType<{
funcFoo: () => 'foo';
recordBar: Record<string, unknown>;
promiseBaz: Promise<unknown>;
}>(camelcaseKeys({
func_foo: () => 'foo',
record_bar: {foo: 'bar'},
promise_baz: new Promise(resolve => {
resolve(true);
}),
}));

expectType<[
() => 'foo',
Record<string, unknown>,
Promise<unknown>,
]>(camelcaseKeys([
() => 'foo',
{foo: 'bar'},
new Promise(resolve => {
resolve(true);
}),
]));

0 comments on commit 71087d6

Please sign in to comment.