gpt4 book ai didi

如果我导入文件,TypeScript 找不到在类型声明中声明的变量

转载 作者:行者123 更新时间:2023-12-03 23:48:05 27 4
gpt4 key购买 nike

我做了一个非常简单的库,其中包含一个 .d.ts ( source ) 具有以下结构(我省略了细节,因为文件工作正常,这可能是我项目中的配置问题):

// Some helper types and interfaces

type TranslationFunction = /* ... */;

export { TranslationFunction };

然后,我做 npm i -D embed-i18n-webpack-plugin将软件包安装到我自己的项目中并创建一个文件 typings/translation.d.ts声明一个全局 t类型变量 TranslationFunction喜欢跟随:
import { TranslationFunction } from "embed-i18n-webpack-plugin";

declare const t: TranslationFunction;

使用 VSCode,我可以将鼠标悬停在 t 上在这个文件中,它告诉我它具有我原始 index.d.ts 中定义的正确类型.这意味着当我在这个文件中时,它会正确地找到它。

在同一 typings目录,我还有一些其他文件声明常量,但它们从不导入任何内容并按预期工作。

但是,当我尝试使用全局 t 时函数在我的代码中,我收到一个错误说明
Cannot find name 't'. ts(2304)
但是,如果我只是在 typings/translation.d.ts 中评论导入:
// import { TranslationFunction } from "embed-i18n-webpack-plugin";

declare const t: TranslationFunction;

它工作正常,但因为它不知道 TranslationFunction ,它折叠成 any .

也许我的包的类型声明文件有误,应该包含一些 declare module ?在 npm 上发布类型声明时,我并不是真的 100% 确定行为,我通常在纯 TS 中使用它们,所以它工作正常。这是我第一次在另一个类型声明文件中使用一个。

如果它可能相关,这是我的 tsconfig.json :
{
"compilerOptions": {
"allowJs": true,
"allowSyntheticDefaultImports": true,
"jsx": "preserve",
"lib": ["dom", "es2017"],
"module": "esnext",
"moduleResolution": "node",
"noEmit": true,
"noUnusedLocals": true,
"noUnusedParameters": false,
"noImplicitAny": false,
"preserveConstEnums": true,
"removeComments": false,
"strictFunctionTypes": false,
"resolveJsonModule": true,
"skipLibCheck": true,
"sourceMap": true,
"strict": true,
"experimentalDecorators": true,
"target": "esnext",
"extendedDiagnostics": true,
"paths": {
"$common/*": ["../Common/*"],
"$config": ["./config"],
"$game/*": ["./src/game/*"],
"$containers/*": ["./src/containers/*"],
"$phaser/*": ["./src/phaser/*"],
"$network/*": ["./src/network/*"],
"$pages/*": ["./src/pages/*"],
"$components/*": ["./src/components/*"],
"$helpers/*": ["./src/helpers/*"],
"$rematch/*": ["./src/rematch/*"],
"$hooks/*": ["./src/hooks/*"],
"$types/*": ["./src/types/*"],
"$src/*": ["./src/*"]
},
"rootDir": ".",
"baseUrl": "."
},
"exclude": ["**/node_modules/*", "build", "coverage"]
}

最后,我尝试了一些方法,看看是否能解决我的问题:
  • 在我的 typings/translate.d.ts 中复制我的包类型声明的内容--> 工作正常
  • 添加一些随机 declare module "ember-i18n-webpack-plugin --> 同样的错误
  • 最佳答案

    导入声明文件并使它们全局可用有点奇怪,如下所示:

    declare const t: import("embed-i18n-webpack-plugin").TranslationFunction;

    这应该是您需要做的全部。如果 Typescript 中包含传统导入,则不会将声明注册为全局声明,因此您需要使用此导入样式。这确实需要 typescript 版本 >= 2.9

    关于它的文档:
    https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-9.html#import-types

    关于如果我导入文件,TypeScript 找不到在类型声明中声明的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61386777/

    27 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com