使用 TypeScript 函数返回 JSON 对象
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/43523645/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Return JSON object with TypeScript function
提问by Hulothe
I discovered TypeScript recently and I try to convert my existing JavaScript code to TypeScript.
我最近发现了 TypeScript,并尝试将现有的 JavaScript 代码转换为 TypeScript。
I have a function that retrieves information from a string (data
), puts it in a JSON object (json
) and returns it. But when using TypeScript and not specifying a return type, I get the following error in Eclipse:
我有一个函数可以从字符串 ( data
)中检索信息,将其放入 JSON 对象 ( json
) 并返回它。但是当使用 TypeScript 而不指定返回类型时,我在 Eclipse 中收到以下错误:
No best common type exists among return expressions
返回表达式中不存在最佳公共类型
It disappears when I add any
return type, but I think this isn't a good solution (too generic). And I couldn't find a "json" or "object" type.
当我添加any
返回类型时它消失了,但我认为这不是一个好的解决方案(太通用了)。而且我找不到“json”或“object”类型。
My question is: what return type should I use?
我的问题是:我应该使用什么返回类型?
Here is the function:
这是函数:
function formaterDonnees(data: string) { // or (data: string): any
// final json object
var json = {
y: {
"vars": [],
"smps": [],
"data": []
}
};
// ...
// processing data...
// ...
// put new variables in JSON (not real values below)
json.y.data = ["data"];
json.y.smps = ["smps"];
json.y.vars = ["vars"];
return json;
};
回答by Nitzan Tomer
You can indeed specify that you return object
(new to typescript 2.2), but you can create a type for your return value:
您确实可以指定您返回object
(新的 typescript 2.2),但您可以为您的返回值创建一个类型:
type MyReturnTypeItem = {
vars: string[];
smps: string[];
data: string[];
}
type MyReturnType = {
[name: string]: MyReturnTypeItem;
}
function formaterDonnees(data: string): MyReturnType {
var json = {
y: {
"vars": [],
"smps": [],
"data": []
}
};
// put new variables in JSON (not real values below)
json.y.data = ["data"];
json.y.smps = ["smps"];
json.y.vars = ["vars"];
return json;
};
(操场上的代码)
Also, while I used type aliasyou can do the same with interfaces:
interface MyReturnTypeItem {
vars: string[];
smps: string[];
data: string[];
}
interface MyReturnType {
[name: string]: MyReturnTypeItem;
}