#Help needed pinpointing and addressing a type error

15 messages · Page 1 of 1 (latest)

odd egret
#

Hello,

When running the included code snippet

I am receiving the following error:

TS2322: Type
{ [x: string]: AggregationQuerySortDirection | undefined; }
is not assignable to type  Record<string, AggregationQuerySortDirection> 
 string  index signatures are incompatible.
Type  AggregationQuerySortDirection | undefined  is not assignable to type  AggregationQuerySortDirection 
Type  undefined  is not assignable to type  AggregationQuerySortDirection 
sortParams.ts(15, 3): The expected type comes from property  preparedKeys  which is declared here on type  SortParamsInput

(see attachment for a better formatted representation of the error message)

Could you help me understand what is causing it and how to fix it, please?

Thank you

copper baneBOT
#
bovvshock#0

Preview:```ts
export type AggregationQuerySortDirection = -1 | 1

export type SortingFields = Record<
string,
AggregationQuerySortDirection

export type SortParamsInput = {
sortingFields: SortingFields
allowedFields: string[]
uniqueFields: string[]
index: number
addIdF
...```

odd egret
#

@ashen hamlet ping

twin dome
#

@odd egret the issue is that sortingFields[key] is AggregationQuerySortDirection | undefined (at least when you enable noUncheckedIndexedAccess)

#

i'd probably refactor this, but it should give you an idea of how to approach things:

copper baneBOT
#
mkantor#0

Preview:```ts
export type AggregationQuerySortDirection = -1 | 1

export type SortingFields = Record<
string,
AggregationQuerySortDirection

export type SortParamsInput = {
sortingFields: SortingFields
allowedFields: string[]
uniqueFields: string[]
index: number
addIdF
...```

odd egret
odd egret
twin dome
#

here's a simpler example:

copper baneBOT
#
mkantor#0

Preview:ts declare const x: Record<string, number> const y = x["a"] // ^?

twin dome
#

y is number | undefined there. not because of anything related to the key ('a'), but y is accessed through x's index signature

ashen hamlet
#

The problem is that Typescript doesn't track the source of sortingFields[key] <- sortingFieldKeys <- Object.keys(sortingFields) and use that to narrow away the undefined

#

noUncheckedIndexedAccess is not really usable because of this.

#

I'd personally turn it off