Returns a JSON object with TypeScript function
I recently discovered TypeScript and I am trying to convert my existing JavaScript code to TypeScript.
I have a function that fetches information from a string ( data
), puts it into a JSON object ( json
) and returns it. But when using TypeScript and not specifying the return type, I get the following error in Eclipse:
There is no best general type among return expressions
It disappears when I add the return type any
, but I think this is not a good solution (too general). And I couldn't find the type "json" or "object".
My question is , what type of return value should I use?
Here's 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;
};
source to share
You can indeed specify what you are returning 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;
};
( playground code )
Also, while I was using the alias type , you can do the same with interfaces :
interface MyReturnTypeItem {
vars: string[];
smps: string[];
data: string[];
}
interface MyReturnType {
[name: string]: MyReturnTypeItem;
}
source to share