#How to filter a Record<string, string> by key value?

6 messages · Page 1 of 1 (latest)

narrow shuttle
#

I am trying to filter a Record<string, string> by key value using the following code:

let records = someFunctionThatReturnsRecord();
records = Object.keys(records).filter((key) => k.indexOf("something") > -1).reduce((curr, key) => { return Object.assign(curr,  { [key] : records[key]})}, {});

But I'm getting this error when I try to compile the code:
Overload 1 of 2, '(o: {}): string[]', gave the following error.
Argument of type 'Record<string, string> | undefined' is not assignable to parameter of type '{}'.
Type 'undefined' is not assignable to type '{}'.
Overload 2 of 2, '(o: object): string[]', gave the following error.
Argument of type 'Record<string, string> | undefined' is not assignable to parameter of type 'object'.
Type 'undefined' is not assignable to type 'object'.

I'm not sure what to make of the error. I'm unable to find anything about the error on search. Could someone please point me in the right direction. I'm new to typescript, but not to javascript and programming in general.

lapis hinge
#

@narrow shuttle Might help if you made a playground that reproduces the issue; I tried with taking a guess at your records type, but it didn't reproduce the issue:

modern hatchBOT
#
retsam19#0

Preview:ts declare let records: Record<string, string> records = Object.keys(records) .filter(key => key.indexOf("something") > -1) .reduce((curr, key) => { return Object.assign(curr, {[key]: records[key]}) }, {})

lapis hinge
#

... but also fairly likely that you're just going to have to cast

#

These sort of object manipulations are tricky in a type-safe way because 1) Object.keys returns string[] (because of excess keys) and 2) because building an object with reduce is a tricky pattern for types:

#

The initial value for the reducer is often not assignable to the final type which often has required keys and there really isn't a safe way to type a reducer that starts out empty but should be populated at the end.