首页 > 解决方案 > quicktype json schema to typescript just-type in custom function

问题描述

我有一个使用 quicktype API 的函数。它可以工作,但我想使用“just-types”选项来只保留打字稿接口(没有类和函数)。

这是我的代码:

async function* getFiles(dir) {
  const dirents = await readdir(dir, { withFileTypes: true });
  for (const dirent of dirents) {
    const res = resolve(dir, dirent.name);
    if (dirent.isDirectory()) {
      yield* getFiles(res);
    } else {
      yield res;
    }
  }
}

(async () => {
  const directoryPath = join(__dirname, "XML")

  for await (const file of getFiles(directoryPath)) {
    const filename = basename(file);
    const filePathArray = file.split('\\');
    const foldername = filePathArray[filePathArray.length - 2];

    if (!fs.existsSync(join(__dirname, 'interfaces', foldername))){
      fs.mkdirSync(join(__dirname, 'interfaces', foldername));
    }
    const interfaceName = filename.split('.')[0];

    const schemaInput = new JSONSchemaInput(new q.JSONSchemaStore());
    schemaInput.addSource({ name: interfaceName, schema: fs.readFileSync(file, "utf8")});

    const inputData = new InputData();
    inputData.addInput(schemaInput);

    quicktype({inputData, lang: new TypeScriptTargetLanguage()}).then(function (data) {
      fs.writeFile(join(__dirname, 'interfaces', foldername, interfaceName + '.ts'), data.lines.join('\n'), function () {});
    });
  }
})()

我已经看到 TypeScriptRenderer 类可以将布尔值“justTypes”作为第三个参数,但我不知道如何使其工作。

我试过传递所有的论点:

TypeScriptRenderer(new TypeScriptTargetLanguage(), ??, { justTypes: true });

第二个参数是 RenderContext。我不知道如何实例化它。

有人知道如何使它工作吗?

标签: quicktype

解决方案


如果其他人偶然发现这个寻找类似的答案,你可以这样做

quicktype({ lang: new TypeScriptTargetLanguage(), inputData, rendererOptions: { 'just-types': 'true' } });

推荐阅读