Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Improve TS typings for filterObject using TS 4.7 Instantiation Expressions #699

Closed
nelsonni opened this issue Mar 30, 2022 · 0 comments · Fixed by #806 or #807
Closed

Improve TS typings for filterObject using TS 4.7 Instantiation Expressions #699

nelsonni opened this issue Mar 30, 2022 · 0 comments · Fixed by #806 or #807
Assignees
Labels
feature Feature requests or improvements

Comments

@nelsonni
Copy link
Member

Is your feature request related to a problem? Please describe.
The return type for filterObject() is subtly incorrect:

export const filterObject = <V, T extends Record<string, V>>(obj: T, filter: string[]): T | Record<string, never> => {
return Object.entries(flattenObject(obj))
.filter(([key]) => filter.includes(key))
.reduce((accumulator, [k, v]) => ({ ...accumulator, [k]: v }), {});
}

Although the possibility exists for filtering to result in an empty object (i.e. Record<string, never>), this forces us to provide an initialValue in the Array.reduce() which incorrectly allows the TypeScript compiler to infer that all inputs can become {}.

Describe the solution you'd like
To improve the typings, we can change the return type to be the flattened object resulting from flattenObject():

ReturnType<typeof flattenObject<T>>

However, this type definition requires using Instantiation Expressions which will be added in the TypeScript 4.7 release.

Additional context
The use of type arguments for generic functions or generic constructions (i.e. Instantiation Expressions), currently throws errors from @typescript-eslint/eslint-plugin. ehaynes99/typescript-eslint-instantation-expressions includes a minimum reproduction build for these ESLint errors in anticipation of TS 4.7.

@nelsonni nelsonni added the feature Feature requests or improvements label Mar 30, 2022
@nelsonni nelsonni self-assigned this Mar 30, 2022
@nelsonni nelsonni linked a pull request Jun 7, 2022 that will close this issue
5 tasks
@nelsonni nelsonni mentioned this issue Jun 7, 2022
@nelsonni nelsonni linked a pull request Jun 13, 2022 that will close this issue
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
feature Feature requests or improvements
Projects
None yet
1 participant