Skip to content

Commit 3335ece

Browse files
committed
Fix #15540: Throw error when importing @types
Fix issue: #15540 - Modify checker; external imports to account for imported modules containing '@types/'. - Add diagnostic message. - Add test case
1 parent 687ab54 commit 3335ece

File tree

5 files changed

+47
-0
lines changed

5 files changed

+47
-0
lines changed

src/compiler/checker.ts

+5
Original file line numberDiff line numberDiff line change
@@ -1642,6 +1642,11 @@ namespace ts {
16421642
return;
16431643
}
16441644

1645+
if (moduleReference.substr(0, 7) === "@types/") {
1646+
const diag = Diagnostics.Cannot_import_type_declaration_files_Consider_importing_0_instead_of_1;
1647+
error(errorNode, diag, moduleName.substr(7), moduleName);
1648+
}
1649+
16451650
const ambientModule = tryFindAmbientModule(moduleName, /*withAugmentations*/ true);
16461651
if (ambientModule) {
16471652
return ambientModule;

src/compiler/diagnosticMessages.json

+4
Original file line numberDiff line numberDiff line change
@@ -2135,6 +2135,10 @@
21352135
"category": "Error",
21362136
"code": 2710
21372137
},
2138+
"Cannot import type declaration files. Consider importing '{0}' instead of '{1}'.": {
2139+
"category": "Error",
2140+
"code": 2711
2141+
},
21382142

21392143
"Import declaration '{0}' is using private name '{1}'.": {
21402144
"category": "Error",
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
tests/cases/compiler/a.ts(1,21): error TS2711: Cannot import type declaration files. Consider importing 'foo-bar' instead of '@types/foo-bar'.
2+
3+
4+
==== /node_modules/@types/foo-bar/index.d.ts (0 errors) ====
5+
export interface Foo {
6+
bar: string;
7+
}
8+
9+
// This should error
10+
==== tests/cases/compiler/a.ts (1 errors) ====
11+
import { Foo } from "@types/foo-bar";
12+
~~~~~~~~~~~~~~~~
13+
!!! error TS2711: Cannot import type declaration files. Consider importing 'foo-bar' instead of '@types/foo-bar'.
14+
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
//// [tests/cases/compiler/importDeclTypes.ts] ////
2+
3+
//// [index.d.ts]
4+
export interface Foo {
5+
bar: string;
6+
}
7+
8+
// This should error
9+
//// [a.ts]
10+
import { Foo } from "@types/foo-bar";
11+
12+
13+
//// [a.js]
14+
"use strict";
15+
exports.__esModule = true;
+9
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
2+
// @filename: /node_modules/@types/foo-bar/index.d.ts
3+
export interface Foo {
4+
bar: string;
5+
}
6+
7+
// This should error
8+
// @filename: a.ts
9+
import { Foo } from "@types/foo-bar";

0 commit comments

Comments
 (0)