繁体   English   中英

代码转换时,TypeScript 的接口参数不起作用

[英]Interface argument of TypeScript is not working when the code is transpiled

我在名为 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

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

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

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

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM