在 Angular Typings.d.ts 中定义多个模块的问题

Rob*_*ier 0 typescript typescript-typings angular

这是我typings.d.ts来自 Angular 6 项目的文件:

import { Injectable, InjectableDecorator, HostBinding, HostBindingDecorator, HostListener, HostListenerDecorator } from '@angular/core';

// Those decorators are declared with `any` type by default. Because of that
// `no-unsafe-any` TSLint rule reports errors on for example `@Injectable`
// decorator. Below declarations fix that.
declare module '@angular/core' {
    export interface InjectableDecorator {
        (providedIn?: any | 'root' | null): ClassDecorator;
    }
    export const Injectable: InjectableDecorator;

    export interface HostBindingDecorator {
        (hostPropertyName?: string): PropertyDecorator;
    }
    export const HostBinding: HostBindingDecorator;

    export interface HostListenerDecorator {
        (eventName: string, args?: string[]): MethodDecorator;
    }
    export const HostListener: HostListenerDecorator;
}

// Allows to import JSON files inside TypeScript files
declare module '*.json' {
    const value: any;
    export default value;
}
Run Code Online (Sandbox Code Playgroud)

最后一个声明'*.json应该允许我在 TypeScript 文件中导入 JSON 文件(更多细节在这里)。它不起作用 - 当我导入 JSON 文件时,TypeScript 编译器报告错误:

ERROR in src/app/core/internationalization/build-time-translate-loader.ts(8,26): error TS2307: Cannot find module '../../../assets/i18n/translations.json'
Run Code Online (Sandbox Code Playgroud)

奇怪的是,一旦我将declare module '*.json' { ... }部分从typings.d.ts任何其他.d.ts文件移动到任何其他文件,例如json.d.ts编译器停止抱怨并且 JSON 正确导入而没有错误。当我将declare module '@angular/core' { ... }部分移出另一个文件时,也会发生同样的情况。这让我假设问题出在两个声明共存于一个文件中。

与TypeScript 文档说明相反,您可以在单个.d.ts文件中声明多个模块:

我们可以使用顶级导出声明在自己的 .d.ts 文件中定义每个模块,但将它们编写为一个更大的 .d.ts 文件会更方便。为此,我们使用类似于环境命名空间的构造,但我们使用模块关键字和模块的引用名称,这些名称将在以后的导入中可用。例如:

declare module "url" {
    export interface Url {
        protocol?: string;
        hostname?: string;
        pathname?: string;
    }

    export function parse(urlStr: string, parseQueryString?, slashesDenoteHost?): Url;
}

declare module "path" {
    export function normalize(p: string): string;
    export function join(...paths: any[]): string;
    export var sep: string;
}
Run Code Online (Sandbox Code Playgroud)

这正是我正在做的。为什么它不起作用,当两者declare module都在同一个文件中时?

Mat*_*hen 5

typings.d.ts被视为外部模块,因为它包含顶级导入。因此,declare module "..." { ... }文件中的每个语句都被视为模块扩充,而不是模块的原始声明。"*.json"由于没有"*.json"可用的原始声明,因此丢弃了的扩充,不幸的是,当在.d.ts文件中发生这种情况时,您不会收到错误;我不确定是否有充分的理由。将 放在declare module "*.json"没有顶级导入的文件中是正确的解决方案。不幸的是,这些都没有被正确记录。