#String index signature lost?

16 messages · Page 1 of 1 (latest)

jagged abyssBOT
#
Daniell#4062

Preview:ts export const getValueByIdentifier = ( source: Record<string, unknown>, identifier: string ) => { return identifier .split(".") .reduce<unknown>( (prev, curr) => (prev || source)[curr], undefined ) }

umbral nacelle
#

Where does it get {} from and any idea how to solve it?

hollow furnace
#

if prev is nullish then prev || source evaluates to source

#

else if it's not nullish (i.e. if it's {}) it evaluates to prev

#

but also

jagged abyssBOT
hollow furnace
#

!ts

jagged abyssBOT
#
export const getValueByIdentifier = (source: Record<string, unknown>, identifier: string) => {
  return identifier
    .split('.')
    .reduce((prev, curr) => prev[curr], source);
//                          ^^^^^^^^^^
// No overload matches this call.
//   Overload 1 of 3, '(callbackfn: (previousValue: string, currentValue: string, currentIndex: number, array: string[]) => string, initialValue: string): string', gave the following error.
//     Type 'unknown' is not assignable to type 'string'.
//   Overload 2 of 3, '(callbackfn: (previousValue: Record<string, unknown>, currentValue: string, currentIndex: number, array: string[]) => Record<string, unknown>, initialValue: Record<string, unknown>): Record<...>', gave the following error.
//     Type 'unknown' is not assignable to type 'Record<string, unknown>'.
};```
hollow furnace
#

!ts

umbral nacelle
hollow furnace
#

i don't think so

hollow furnace
#

so the issue is that values in the object are not guaranteed to be objects

#

which is correct

#

you might want to handle that case explicitly