Skip to content

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

@nelsonni

Description

@nelsonni

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.

Metadata

Metadata

Assignees

Labels

featureFeature requests or improvements

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions