I discovered TypeScript recently and I try to convert my existing JavaScript code to 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:
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.
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;
};
I discovered TypeScript recently and I try to convert my existing JavaScript code to 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:
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.
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;
};
Share
Improve this question
asked Apr 20, 2017 at 15:19
HulotheHulothe
7641 gold badge6 silver badges17 bronze badges
1 Answer
Reset to default 15You can indeed specify that you return object
(new to typescript 2.2), but you can create a type for your return value:
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;
};
(code in playground)
Also, while I used type alias you can do the same with interfaces:
interface MyReturnTypeItem {
vars: string[];
smps: string[];
data: string[];
}
interface MyReturnType {
[name: string]: MyReturnTypeItem;
}