【发布时间】:2018-06-10 06:29:40
【问题描述】:
注意: 我知道有很多关于这个主题的帖子,而且我已经查看了很多没有成功的帖子(请参阅我在这篇文章的底部)。
我正在尝试使用 Visual Studio Code 在 TypeScript 中运行一个非常简单的测试,在其中我在一个文件中声明一个类并将其导入另一个文件。但是,我继续遇到我要导入的文件无法识别从其他文件导出的类的方法的问题。
此时我收到的确切错误消息是:
[ts] 属性 'getFirstName' 不存在于类型 'typeof "module-test/src/OtherClass"' 上。
[ts] 属性 'getLastName' 在类型 'typeof "module-test/src/OtherClass"' 上不存在。
我使用的是 Node 9.3.0 和 TypeScript 2.6.2。
非常感谢任何人都可以提供给我的任何指导!
main.ts
import * as Other from "./OtherClass";
class myApp
{
public async start()
{
console.log("Starting application");
try
{
let firstName = await Other.getFirstName();
console.log("First Name: " + firstName);
let lastName = await Other.getLastName();
console.log("Last Name: " + lastName);
}
catch (error)
{
console.error("Unable to get name: " + error)
}
console.log("Ending application");
}
}
const app = new myApp();
app.start();
OtherClass.ts
class Other
{
getFirstName(): string
{
return "John";
}
getLastName(): string
{
return "Doe";
}
}
export { Other };
我尝试过的事情
- 通过声明导出
export class Other
{
getFirstName(): string
{
return "John";
}
getLastName(): string
{
return "Doe";
}
}
- 导出单个函数
class Other
{
export function getFirstName(): string
{
return "John";
}
export function getLastName(): string
{
return "Doe";
}
}
- 多个导出语句
module.exports = Other;
export { Other };
export * from "OtherClass";
- 多个导入语句
import * as Other from "./OtherClass";
import { Other } from "./OtherClass";
配置文件 package.json
{
"name": "module-test",
"version": "1.0.0",
"description": "Simple test of exporting and importing modules",
"main": "./lib/main.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "John Doe",
"license": "ISC",
"dependencies": {
"typescript": "^2.6.2"
},
"devDependencies": {
"@types/node": "^8.5.2",
"@types/typescript": "^2.0.0"
}
}
tsconfig.json
{
"compilerOptions": {
/* Basic Options */
"target": "es2016", /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', or 'ESNEXT'. */
"module": "commonjs", /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', or 'ESNext'. */
"outDir": "./lib/", /* Redirect output structure to the directory. */
"strict": true, /* Enable all strict type-checking options. */
"inlineSourceMap": true, /* Emit a single file with source maps instead of having a separate file. */
"inlineSources": true /* Emit the source alongside the sourcemaps within a single file; requires '--inlineSourceMap' or '--sourceMap' to be set. */
}
}
引用的文章
- Property 'Server' does not exist on type 'typeof "http"'
- Node.js ES6 how to export class from module?
- Difference between "module.exports" and "exports" in the CommonJs Module System
- how to properly create and import node modules in typescript
- TypeScript - Export and import modules
- https://www.typescriptlang.org/docs/handbook/modules.html
【问题讨论】:
标签: javascript node.js typescript