代码之家  ›  专栏  ›  技术社区  ›  Limbo

TypeScript:基于对象创建接口

  •  0
  • Limbo  · 技术社区  · 8 年前

    我想创建文件工厂(例如,在我的例子中是带有翻译的JSON)。

    {
        "field": "",
        "group": {
            "field_1": "",
            "field_2": ""
        },
        ...
    }
    

    我希望创建一个包含翻译中所有字段的JSON模板,然后用每个语言环境的一些默认值实例化它,以使我的应用程序不会错过任何翻译字段。好吧,这很简单,在输出时我有几个文件(基于区域设置的计数),名为 <locale>.json ,例如。 en.json 有些内容是这样的:

    {
        "field": "en:field",
        "group": {
            "field_1": "en:group.field_1",
            "field_2": "en:group.field_2",
        },
        ...
    }
    

    现在,我想基于我的JSON模板创建一个类型或接口,以允许在IDE的快速提示中显示我的翻译字段(例如VS代码)。

    有没有可能以方便的方式做这件事?我知道我可以动态地创建一个 .ts 文件与导出接口,但这不是那么好,因为所有 ts

    为了清楚起见,我想得到一个这样的接口

    interface IMyCoolInterface {
        field: string,
        group: {
            field_1: string,
            field_2: string,
        },
        ...
    }
    
    2 回复  |  直到 8 年前
        1
  •  7
  •   jcalz    8 年前

    你可以用这个 --resolveJsonModule compiler option

    import * as translationTemplate from 'template.json';
    

    并使用 typeof type query :

    type Translation = typeof translationTemplate;
    

    如果一切顺利,如果你声明一个变量是 Translation 您应该得到IDE提示:

    declare const t: Translation; // or whatever
    t.field; // hinted at you
    t.group.field_1; // likewise
    

        2
  •  1
  •   NEO    8 年前

    我认为一个好的解决办法是:

    • 首先根据JSON数据结构声明一个或多个接口

    一个简单实现的例子是:

    interface IGroup{
     field_1:string;
     field_2:string;
    }
    
    interface IMyCoolInterface{
     field:string;
     group:IGroup;
    }
    

    如果需要组的JSON数组:

    interface IMyCoolInterface{
     field:string;
     groups:Array<IGroup>;
    }
    

    首先实现IGroup接口:

    class Group implements IGroup{
     field_1:string;
     field_2:string;
     construdtor(field_1:string,field_2:string)
     {
      this.field_1=field_1;
      this.field_2=field_2;
     }
    }
    

    现在实现IMyCoolInterface(假设您需要一个组的JSON数组):

    class MyCoolClass implements IMyCoolInterface
    {
     field:string;
     groups:Array<IGroup>;
     constructor(field:string,groups?:Array<IGroup>)
     {
      this.field=field;
      this.groups=groups || [];
     }
     //add some methods
     addGroup(group:IGroup)
     {
      this.groups.push(group)
     }
    }
    

    这是一种使用接口处理JSON的简单方法。

        3
  •  0
  •   Akshay Vijay Jain    5 年前

    type Tob = typeof ob;
    
    var ob = {
      a: 1,
      b: 'string',
    };
    

    enter image description here

    // my tsconfig.json
    {
      "compilerOptions": {
        "allowJs": true,
        "allowSyntheticDefaultImports": true,
        "esModuleInterop": true,
        "isolatedModules": true,
        "jsx": "react",
        "lib": ["es6"],
        "moduleResolution": "node",
        "noEmit": true,
        "strict": true,
        "target": "esnext"
      },
      "exclude": [
        "node_modules",
        "babel.config.js",
        "metro.config.js",
        "jest.config.js"
      ]
    }
    
    推荐文章