英文:
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" ]]
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论