使用TypeScript函数返回JSON对象 [英] Return JSON object with TypeScript function

查看:194
本文介绍了使用TypeScript函数返回JSON对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近发现了TypeScript,然后尝试将现有的JavaScript代码转换为TypeScript.

I discovered TypeScript recently and I try to convert my existing JavaScript code to TypeScript.

我有一个函数,可以从字符串(data)中检索信息,将其放入JSON对象(json)中并返回它.但是,当使用TypeScript而不指定返回类型时,在Eclipse中会出现以下错误:

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

当我添加any返回类型时,它消失了,但是我认为这不是一个很好的解决方案(太通用了).而且我找不到"json"或"object"类型.

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?

这里是函数:

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;

};

推荐答案

您确实可以指定返回object(

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;

};

(操场上的代码)

此外,当我使用类型别名时,您可以对接口:

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

这篇关于使用TypeScript函数返回JSON对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆