Return JSON object with TypeScript function Return JSON object with TypeScript function json json

Return JSON object with TypeScript function


You 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;}