【问题标题】:Interface argument of TypeScript is not working when the code is transpiled转译代码时,TypeScript 的接口参数不起作用
【发布时间】:2020-02-18 23:40:59
【问题描述】:

我在一个名为 get() 的类中有一个方法

import optionsInst from "./options";
get(url, opt: optionsInst){}

optionsInst 是另一个文件的接口

export interface Options {
  tipoRespuesta?: "json" | "arrayBuffer";
  params?: string;
  data?: string;
  headers?: HeadersInit;
}
export default Options;

我的 tsconfig 是:

{
  "compilerOptions": {
    "target": "es6",
    "allowSyntheticDefaultImports": true,
    "sourceMap": true,
    "outDir": "./dist",
    "module": "CommonJS",
    "declaration": true,
    "allowJs": true
  },
  "exclude": ["node_modules"]
}

转译我使用npm run build 并生成一个 dist 文件夹。 为了测试它,我创建了一个新文件并运行npm test.js

var CL = require("../dist/index.js");

let instancia = new CL("https://reqres.in/api/");
instancia.get("users").then(console.log);

错误是这样的:

  if (utils.isEmpty(opt.headers)) {
                              ^

TypeError: Cannot read property 'headers' of undefined

【问题讨论】:

    标签: javascript typescript interface transpiler


    【解决方案1】:

    如果以下行在类中的get(url, opts: optionsInst) 方法内

    if (utils.isEmpty(opt.headers)) {
    

    那么你的问题是你在没有定义 ops 参数的情况下调用它,这里:

    instancia.get("users").then(console.log);
    

    错误只是说它无法读取属性opt.headers,因为optundefined

    您实际上应该在上面的那一行收到一个 Typescript 错误,告诉您调用中缺少 opts 参数 - 检查一下。但是 Typescript 仍然会编译代码,只是在你运行时导致运行时错误——显然 Typescript 试图帮助你避免的事情!

    【讨论】:

      猜你喜欢
      • 2020-02-15
      • 2017-06-30
      • 2017-02-08
      • 2013-01-08
      • 2018-11-15
      • 2012-10-04
      • 1970-01-01
      • 2020-03-19
      • 2011-03-09
      相关资源
      最近更新 更多