打字稿中的接口并将其转换为 Javascript

时间:2021-07-31 08:47:26

标签: javascript typescript interface

是否可以将 typescript 的 interface 转换为 Javascript。如果是,那么如何将下面提到的打字稿代码转换为 Javascript。

interface xyz{
  something? : string, 
  somethingStyle? : Textstyle
} 

2 个答案:

答案 0 :(得分:1)

不,Javascript 中根本不存在接口。它们仅用于编译器。

答案 1 :(得分:0)

虽然您的问题没有说明这一点,但我假设您希望以某种自动方式将编译时检查转换为运行时检查。考虑到这一点,我发现 these notes 将用作此答案的基础。

从您的示例开始并修饰 HeaderBar::set_spacing(0) 可能是什么,我们创建 Textstyle

xyz.ts

然后为我们的示例安装其余的依赖项(下面是一个 shell 会话):

interface Textstyle {
  bold: boolean;
  font: string;
}

export interface xyz {
  something?: string;
  somethingStyle?: Textstyle;
}

如果我们查看 $ echo '{"private":true}' >package.json $ npm install --save-dev typescript @tsconfig/recommended ts-json-schema-generator $ echo '{"extends":"@tsconfig/recommended/tsconfig.json"}' >tsconfig.json $ npx ts-json-schema-generator --path 'xyz.ts' >xyz_schema.json ts-json-schema-generator 的输出,我们会发现:

xyz_schema.json

由于 JSON 模式是一种定义的格式,我们可以使用多种工具来验证我们的对象。以下是我与 Ajv 一起整理的内容:

{
  "$ref": "#/definitions/xyz",
  "$schema": "http://json-schema.org/draft-07/schema#",
  "definitions": {
    "xyz": {
      "additionalProperties": false,
      "properties": {
        "something": {
          "type": "string"
        },
        "somethingStyle": {
          "additionalProperties": false,
          "properties": {
            "bold": {
              "type": "boolean"
            },
            "font": {
              "type": "string"
            }
          },
          "required": [
            "bold",
            "font"
          ],
          "type": "object"
        }
      },
      "type": "object"
    }
  }
}

输出:

const Ajv = require("ajv");
const schema = require("./xyz_schema.json");

const ajv = new Ajv();
const validate = ajv.compile(schema);

const x1 = {
  something: "hello world",
  somethingStyle: {
    bold: true,
    font: "comic sans",
  },
};

const x2 = {
  wibbles: "wobble",
};

const testCases = [x1, x2];

testCases.forEach((x, i) => {
  const valid = validate(x);
  if (valid) {
    console.log(`test case ${i} is valid`);
  } else {
    console.error(`test case ${i} is invalid`);
    console.error(validate.errors);
  }
});
相关问题