获取返回对象的函数的类型如何?

huangapple go评论84阅读模式
英文:

how to get type of functions which return object

问题

我想知道如何从函数返回的内容中获取类型。该函数返回一个带有两个键值的对象:X 和 y。在我的 getItem 函数中,我只需要 X 的类型。我不想使用接口 SelectedItems,因为将来我将把这个接口传递给 Pinia store 用于 vue.js,以获取此 getter 的全局类型。有没有办法做到这一点?

function getItem(value: string) {
  interface SelectedItems {
    x: animals | null; // 这里需要 X 的类型
    y: fruits
  }

  return store.getters['stuff/product'](value) as SelectedItems;
}

function setMapping(aniamals: typeof getItem) { // 这里我想获取键 'x' 的类型
   ...
}
英文:

I was wondering how can get the type from what function returned. The function return object with
two keys: X and y. In my getItem function I need only type of X.
I don't want to use the interface SelectedItems because in the future I will pass this interface to Pinia store for vue.js to have a global type for this getter.
Any idea how to make it?

function getItem(value: string) {
  interface SelectedItems {
    x: animals | null; => object
    y: fruits
  }

  return store.getters['stuff/product'](value) as SelectedItems;
}

function setMapping(aniamals: typeof getItem) { // Here I wouldlike to get to key 'x'
   ...
}

答案1

得分: 1

获取对象的字段,您可以使用 Object.keys(your_object)Object.entries(your_object)。即使您从 Pinia Store 动态获取类型,这也应该有效。

示例:

const obj = {a: 1, b: "Hello"} 
Object.entries(obj)
// [["a", 1], ["b", "Hello"]]
英文:

To get fields of an object, you can use Object.keys(your_object) or Object.entries(your_object). This should work even when you are getting your types dynamically from the Pinia Store.

Example:

const obj = {a: 1, b: "Hello"} 
Object.entries(obj)
// [[ "a", 1 ], [ "b", "Hello" ]]

huangapple
  • 本文由 发表于 2023年3月31日 03:18:25
  • 转载请务必保留本文链接:https://go.coder-hub.com/75892163.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定