typescript :找不到命名空间

b5buobof  于 2023-03-04  发布在  TypeScript
关注(0)|答案(4)|浏览(598)

我有下面的简单NodeJS代码:

const express = require('express');

const server: express.Application = express();

我正在添加Typescript到我的项目,我是新来的,所以请原谅我。与上述代码我得到以下问题/错误:
对于要求:

var require: NodeRequire (id: string) => any (+1 overload)
'require' call may be converted to an import.

对于express.应用程序使用:

Cannot find namespace 'express'.

如果我将“require”切换为“import”,它会修复命名空间错误,但不再是有效的节点代码,因此不会运行(引发一个关于导入的意外标记的新错误)。
使用Typescript编写类似这样的Node代码以避免这些错误的正确方法是什么?
我的tsconfig.json看起来像这样:

{
  "compilerOptions": {
    "allowJs": true,
    "allowSyntheticDefaultImports": true,
    "alwaysStrict": true,
    "esModuleInterop": true,
    "forceConsistentCasingInFileNames": true,
    "jsx": "preserve",
    "lib": ["dom", "es2017"],
    "module": "esnext",
    "moduleResolution": "node",
    "noEmit": true,
    "noFallthroughCasesInSwitch": true,
    "noImplicitReturns": true,
    "noUnusedLocals": true,
    "noUnusedParameters": true,
    "removeComments": true,
    "resolveJsonModule": true,
    "sourceMap": true,
    "strict": true,
    "target": "esnext",
  },
  "exclude": ["node_modules"],
}
1yjd4xko

1yjd4xko1#

如果您是一个React开发人员,像我一样在这里结束-如果文件中有JSX语法,请尝试将文件的扩展名从.ts更改为.tsx

b5lpy0ml

b5lpy0ml2#

在浪费了大量时间之后,发现这是由于tsconfig文件中的module设置所致,该设置应为:

"module": "commonjs"

这意味着Typescript将输出普通的js模块而不是ES6模块,这意味着代码将作为NodeJS代码正确运行。因此,我能够更改导入的要求,因为它可以编译。

n1bvdmb6

n1bvdmb63#

也许您必须使用 import 而不是 require

import * as express from 'express';
sqyvllje

sqyvllje4#

使用枚举而不是对象

我的代码满足上面提到的所有答案。"module": "commonjs"并且我的文件已经是.tsx文件。
仍然收到此错误。以下是我如何收到此错误的。
在我的有效载荷中,我有一个关键字(形状),有效载荷的一些其他细节依赖于它。

export const SHAPES = {
  SQUARE: "square",
  CIRCLE: "circle",
};

注意:我使用这个SHAPES对象来存储常量
如果您尝试使用对象的值作为接口的类型,则会收到此错误。

interface ICirclePayload {
  shape: SHAPES.CIRCLE;
  details: {
    radius: number;
  };
}

interface ISquarePayload {
  shape: SHAPES.SQUARE;
  details: {
    length: number;
  };
}

在两个接口中,SHAPES都将出现以下错误

Cannot find namespace 'SHAPES'.ts(2503)

此处的解决方案

object更改为enum

export const enum SHAPES {
  SQUARE = "square",
  CIRCLE = "circle",
}

使用上面的代码,应该可以解决该错误。
考虑阅读What is the difference between enum and object in typescript

相关问题