Home > front end >  How to declare a typed record in TypeScript as return value for a function that returns a record?
How to declare a typed record in TypeScript as return value for a function that returns a record?

Time:10-17

I have a library that offers the following function:

  item(
    id: BigNumberish,
    overrides?: CallOverrides
  ): Promise<[number, number] & { x: number; y: number }>;

I'd like to define the return value in a const-variable in order to receive the value in a typed fashion.

How would I do this?

I have tried this:

const { x: number, y: number } = await data.item(id);

But it will result in an error:

error TS2451: Cannot redeclare block-scoped variable 'number'.

How to do this?

CodePudding user response:

I'm not convinced your function's return type makes sense (what is an array combined with an object?) but regardless you shouldn't need to declare your types when destructuring the response. TypeScript will infer that x and y are numbers based on the function signature

const { x, y } = await data.item(id);

Is sufficient to know that x and y are number types

  • Related