gpt4 book ai didi

javascript - 找不到 Typescript 自己的模块

转载 作者:行者123 更新时间:2023-12-02 23:56:09 25 4
gpt4 key购买 nike

我目前正在学习 TypeScript 并尝试定义我自己的类型。我目前正在使用 .d.ts 文件来声明我的类型。

我创建了一个文件./src/typings/git-types.d.ts:

declare module "git-types" {
export interface GitRepoListItem {
repoName: string;
repoPath: string;
}

export interface GitReturnObject {
value: any;
errorCode: GitErrorCode;
}

export enum GitErrorCode {
UnknownError = 1,
GitNotFound = 2,
NoValidPathGiven = 3,
LocalChangesPreventCheckout = 4,
LocalChangesPreventPull = 5
}

export interface GitCommit {
hash: string;
author: string;
commitDate: string;
commitTime: string;
commitMessage: string;
}
}

现在我尝试导入此模块,以便在另一个文件中使用我的类型CommitHistory.ts:

import { GitCommit } from "git-types";

class CommitHistory {
commitList: GitCommit[] = [];

...
}

但是当我尝试运行我的代码时,编译器失败并给出以下错误:找不到模块:无法解析“./src/CommitHistory.ts”中的“git-types”

正如您在我的 tsconfig.json 文件中看到的,整个“src”文件夹都包含在内:

{
"compilerOptions": {
"target": "es6",
"lib": ["dom", "dom.iterable", "esnext"],
"allowJs": true,
"skipLibCheck": true,
"esModuleInterop": true,
"allowSyntheticDefaultImports": true,
"strict": true,
"forceConsistentCasingInFileNames": true,
"module": "esnext",
"moduleResolution": "node",
"resolveJsonModule": true,
"isolatedModules": true,
"noEmit": true,
"jsx": "preserve",
"experimentalDecorators": true
},
"include": ["src"]
}

我必须如何声明模块才能使用我的类型?

最佳答案

不要将您的类型声明为来自全局模块

src/typings/git-types.d.ts中,不需要编写声明模块“git-types”。只需导出您的类型:

// src/typings/git-types.d.ts
export interface GitRepoListItem {
repoName: string;
repoPath: string;
}
// …

然后,可以使用相对路径导入这些类型:

// src/CommitHistory.ts
import { GitCommit } from "./typings/git-types";

或者,声明现有全局模块的类型

如果您安装了一个真正的 npm 包 git-types,其中仅包含 JavaScript 代码,并且您想自己提供类型,那么您的代码就可以正常工作。

关于javascript - 找不到 Typescript 自己的模块,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55380093/

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