简体   繁体   English

如何在 TypeScript 中将类型化记录声明为返回记录的函数的返回值?

[英]How to declare a typed record in TypeScript as return value for a function that returns a record?

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.我想在 const 变量中定义返回值,以便以类型化的方式接收值。

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?这该怎么做?

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 TypeScript 会根据函数签名推断 x 和 y 是数字

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

Is sufficient to know that x and y are number types足以知道 x 和 y 是number类型

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 TypeScript:如何声明记录或记录数组的类型? - TypeScript: How to declare type for Record or Array of Records? 如何将静态类型的函数记录应用于 typescript 中的参数 - How to apply a statically typed Record of Functions to an argument in typescript 如何在 typescript 中声明带有部分特定键的“记录”类型? - How to declare a "Record" type with partial of specific keys in typescript? TypeScript:function 返回一个扩展 Record 的泛型类型<string, string></string,> - TypeScript: function that returns a generic Type which extends Record<string, string> 如何在打字稿中读取记录的值(正确的方法) - How to read the value of a Record in typescript (the right way) 如何在 Typescript 中为字符串和 boolean 值设置记录 - How to set Record in Typescript for string and boolean value 如何构建一个 typescript function 从另一个 object 返回带有给定键的记录 - How to build a typescript function that returns an record with the given keys from another object TypeScript:为什么输入回调function时这个返回值未知? - TypeScript: Why is this return value unknown when the callback function is typed? 如何在 Typescript 中声明类型化的 object 变量 - How to declare a typed object variable in Typescript 如何声明 function 的类型,该类型返回 function 并在 typescript 中推断类型? - How to declare type for a function, that returns function with inferred type in typescript?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM