Home > Mobile >  Typescript interface type with optional keys of different types
Typescript interface type with optional keys of different types

Time:01-07

Here is the data I receive through the API.

i_1: {count: 1, name: 'name1', price: 35000}
i_2: {count: 1, name: 'name2', price: 30000}
i_3: {count: 1, name: 'nam3', price: 30000}

I defined its type like this.

interface Item {
  count: number;
  name: String;
  price: number;
}

I added that to a type property called Data.

interface Data {
  items?: Item;
 ...etc
}

But I ran into a problem when I tried to use Object.entries.

code

Object.entries(items).map(([key, value]) => ())

The error message is :

No overload matches this call.
  Overload 1 of 2, '(o: { [s: string]: unknown; } | ArrayLike<unknown>): [string, unknown][]', gave the following error.
    Argument of type 'Item | undefined' is not assignable to parameter of type '{ [s: string]: unknown; } | ArrayLike<unknown>'.
      Type 'undefined'enter code here is not assignable`enter code here` to type '{ [s: string]: unknown; } | ArrayLike<unknown>'.
  Overload 2 of 2, '(o: {}): [string, any][]', gave the following error.
    Argument of type 'Item | undefined' is not assignable to parameter of type '{}'.
      Type 'undefined' is not assignable to type '{}'.

Any help would be appreciated.

CodePudding user response:

You're passing a type which might be undefined to Object.entries, to fix this, you can the nullish coalescing operator:

Object.entries(items ?? {}).map(([key, value]) => ())

Also, TypeScript gives a generic type to Object.entries, so if you want to make it use a more precise type, you can either use a cast or refer to the solutions at Typescript Key-Value relation preserving Object.entries type to make your own Entries<T> type for Object.entries

  • Related