javascript - TypeScript 经常出现问题并且更喜欢 import 而不是 require

标签 javascript node.js typescript

只要有可能,我都会尝试使用 import 而不是 require 但在某些情况下,这会破坏类型检查。处理这个问题的正确方法是什么?是否可以导入?不是所有的 require 都可以用 import 替换吗?

Left: Property 'get' does not exist, Right: import instead of require

左:属性“get”不存在...

正确:import * as convict from "convict"; 而不是 require("convict");

左:

"use strict";

import * as Busboy from "busboy";
import * as convcit from "convict";
import * as config from "./config";
import * as express from "express";
import * as helmet from "helmet";
import * as logger from "morgan";
import * as path from "path";

import * as requestDebug from "request-debug";
import * as requestJs from "request";

// [ts] Property 'get' does not exist on type 'typeof "PrizmDoc-Node.js-Sample/config"'.
if (config.get("env") !== "production") {
    requestDebug(requestJs);
}

...

右:

//let convict = require("convict");

import * as convict from "convict";

const config = convict({
    "env": {
        "doc": "The application environment.",
        "format": ["production", "development", "test"],
        "default": "development",
        "env": "NODE_ENV"
    },

...

module.exports = config;

最佳答案

不幸的是,这是您的一个依赖项 convict 的类型问题。查看 @types/convict 来源:

https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/convict/index.d.ts#L122

他们使用 export = ... 导出定义,根据 Typescript 手册:

https://www.typescriptlang.org/docs/handbook/modules.html (请参阅“export =import = require()”标题)

中断 import * from ... 导入。所以,你有点卡在这个上面了。

关于javascript - TypeScript 经常出现问题并且更喜欢 import 而不是 require,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48368325/

相关文章:

javascript - 如何链接到打开的 Accordion ?

javascript - 在 javascript 中,空字符串作为 boolean 值总是 false 吗?

javascript - 通过 JavaScript 函数提交表单

javascript - 使用 Webdriverjs Selenium 加载默认的 chrome 配置文件

typescript - Angular 2 : switchMap not canceling previous http calls

generics - Typescript 无法检测索引签名中泛型方法的参数类型

javascript - 根据数据库值更改记录的颜色,extjs4.2

html - 使用 node.js 在 http ://localhost instead of file://, 上查看站点

javascript - 尝试使用 Nodejs 从 HTML 响应中提取信息

javascript - 如何将 Promise<string> 分配给 String 类型