【问题标题】:typescript: cant declare an interface打字稿:无法声明接口
【发布时间】:2021-02-06 06:33:27
【问题描述】:

我正在使用 typescript,但无法使用另一个文件中声明的接口。
我的global.d.ts 看起来像这样。

declare interface IPropSendEmail {
    from: string,
    to: string,
    subject: string,
    html: string,
}

下面是tsconfig.json

{
    "compilerOptions": {
        "target": "es6",
        "module": "commonjs",
        "outDir": "./build",
        "esModuleInterop": true,
        "declaration": true,
        "strict": true,
        "typeRoots": [
            "types"
        ],
    }
}

目录结构如下所示

    | -- src
            |-- types
                     |-- global.d.ts
            |-- util
                     |-- common.ts
            |-- ...

common.ts 文件中使用它

export async function sendEmail({ from, to, subject, html }: IPropSendEmail) {
     // function code here
     ...
}

【问题讨论】:

  • 这对我们来说信息不足,请提供更多上下文(例如,还有什么文件,您打算如何使用它等)。

标签: typescript declaration typescript-typings


【解决方案1】:

它应该工作。但是,我建议清理配置中奇怪的部分:

在你的tsconfig.json:

  • 删除typeRoots;
  • 添加include
{
    "compilerOptions": {
        "target": "es6",
        "module": "commonjs",
        "outDir": "build",
        "esModuleInterop": true,
        "declaration": true,
        "strict": true
    },
    "include": ["src"]
}

global.d.ts中,关键字declare是没用的:

interface IPropSendEmail {
    from: string,
    to: string,
    subject: string,
    html: string,
}

确保此文件中没有exportimport

【讨论】:

  • 感谢 tsconfig.json 的回复和建议。我使用了declare,这样我就可以在任何文件中使用interface 而无需导入它。我以前用过,只是现在没有那个配置。
  • @mkamranhamid 尝试删除它(declare 关键字)。它会以同样的方式工作。
  • 我想你指的是@Andris 的this。这是一个非常详细的答案,说明为什么使用 declare 是一种不好的做法。
  • @mkamranhamid 不,我是说关键字declare 对界面没有用处。
  • 然后呢?你是说我应该使用export 以便interfacecommon.ts 中对import 可用
猜你喜欢
  • 2019-03-26
  • 1970-01-01
  • 2019-05-28
  • 1970-01-01
  • 2019-03-25
  • 2021-01-20
  • 2017-06-04
  • 1970-01-01
  • 2021-11-22
相关资源
最近更新 更多