Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

relative import cannot resolve to an ambient module

Tags:

typescript

According to typescript documentation (https://www.typescriptlang.org/docs/handbook/module-resolution.html):

A relative import is resolved relative to the importing file and cannot resolve to an ambient module declaration.

but also:

For example, an import statement like import { b } from "./moduleB" in /root/src/moduleA.ts would result in attempting the following locations for locating "./moduleB":

/root/src/moduleB.ts
/root/src/moduleB.tsx
/root/src/moduleB.d.ts
/root/src/moduleB/package.json (if it specifies a "typings" property)
/root/src/moduleB/index.ts
/root/src/moduleB/index.tsx
/root/src/moduleB/index.d.ts"

The line /root/src/moduleB.d.ts seems to me as an ambient module declaration used to resolve the relative import "./moduleB" -> exactly what the documentation denies it does.

Am I missing something here or the documentation is wrong?

like image 897
adrhc Avatar asked Oct 18 '22 07:10

adrhc


1 Answers

Short Answer

The line /root/src/moduleB.d.ts seems to me as an ambient module declaration... Am I missing something here or the documentation is wrong?

You are missing something here. moduleB.d.ts is not an ambient module declaration. Here is an example of a file that contains an ambient module declaration of moduleB.

// someFile.d.ts 

declare module "moduleB" {
    export class b { }
}

The declare keyword specifies an ambient declaration.

Some Details

About the word ambient, the documentation says:

We call declarations that don’t define an implementation “ambient”. Typically, these are defined in .d.ts files.

Ambient declarations include but are not limited to ambient module declarations. A .d.ts file that contains ambient declarations is not an ambient module declaration and does not necessarily contain an ambient module declaration.

For instance, the following greeter.d.ts file contains an ambient class declaration, but it is not an ambient module declaration.

// greeter.d.ts

declare class Greeter {
    constructor(greeting: string);
    greeting: string;
}

The following foobar.d.ts file contains two ambient module declarations of "foo" and "bar", but the file itself is not an ambient module declaration.

// foobar.d.ts

declare module "foo" {       
    export function doFoo(foo: string): string;
}

declare module "bar" {
    export function doBar(bar: string): string;
}

The documentation that you originally cited states that a relative import of "./foo" could not resolve to the above ambient declaration of that module.

Further Details

See: https://www.typescriptlang.org/docs/handbook/modules.html

See also: https://github.com/Microsoft/TypeScript-Handbook/issues/180

See also: https://www.typescriptlang.org/docs/handbook/declaration-files/by-example.html

like image 104
Shaun Luttin Avatar answered Oct 21 '22 08:10

Shaun Luttin