javascript - 是否可以使用 ES6 类作为 Typescript 类型?

标签 javascript typescript

我想做的是:

  • 创建 Typescript 类并将其导出到 .ts 文件中。
  • 将该 .ts 文件编译为 ES6 .js 捆绑文件。
  • 从其他地方的新 .ts 文件中捆绑的 .js 文件导入类。
  • 使用从捆绑文件导入的类作为类型。

这可能吗?如果是这样,我怎样才能实现这一目标?

最佳答案

在您的 tsconfig.json 文件中。您可以设置名为 declaration 的编译器选项为true。然后,当您将 TS 文件编译为 JS 时,它会自动为您创建定义文件(.d.ts)。有了这些文件,您可以使用类型断言将它们导入 TS/JS 项目中的任何位置。

编辑 tsconfig.json 来 self 的 project例如:

{
  "compilerOptions": {
    "module": "commonjs",
    "esModuleInterop": true,
    "target": "es5",
    "experimentalDecorators": true,
    "strict": true,
    "moduleResolution": "node",
    "sourceMap": true,
    "noUnusedLocals":  true,
    "incremental": true,
    "outDir": "dist",
    "tsBuildInfoFile": "dist/.tsBuildInfoFile",
    "baseUrl": ".",
    "resolveJsonModule": true,
    "declaration": true,
    "typeRoots": ["./src/types", "./node_modules/@types"]
  },
  "include": ["src/**/*"],
  "exclude": ["node_modules", "test/**/*"]
}

关于javascript - 是否可以使用 ES6 类作为 Typescript 类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59681908/

相关文章:

javascript - 用于检查所有图像是否已完全加载的 Angular 指令

typescript - Angular 2 (TypeScript) 中的 *ngIf 问题

javascript - 比较两个主干模型之间的差异?

javascript - String.charAt() 在循环中返回 undefined

javascript - 使用 JavaScript 加载页面时如何避免静态网站闪烁

typescript - 如何清理 typescript 缓存?

node.js - 如何通过@types 为作用域/命名空间包安装 TypeScript 声明?

android - 在react-native中从TypeScript调用 native 函数

javascript - keyup 事件监听器中的 jQuery 单击事件监听器

javascript - 悬停效果在 IE9 上不起作用