Skip to content

Commit 13a37a0

Browse files
sadan4fisker
andauthored
prefer-node-protocol: Handle TypeScript import types (#2774)
Co-authored-by: fisker Cheung <[email protected]>
1 parent 7251978 commit 13a37a0

File tree

3 files changed

+48
-0
lines changed

3 files changed

+48
-0
lines changed

docs/rules/prefer-node-protocol.md

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -50,3 +50,11 @@ const fs = process.getBuiltinModule('fs/promises');
5050
//
5151
const fs = process.getBuiltinModule('node:fs/promises');
5252
```
53+
54+
```ts
55+
//
56+
type Fs = import('fs');
57+
58+
//
59+
type Fs = import('node:fs');
60+
```

rules/prefer-node-protocol.js

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,9 @@ const messages = {
1010
};
1111
const NODE_PROTOCOL = 'node:';
1212

13+
/**
14+
@param {import('eslint').Rule.RuleContext} context
15+
*/
1316
const create = context => ({
1417
Literal(node) {
1518
if (!(
@@ -34,6 +37,12 @@ const create = context => ({
3437
)
3538
&& node.parent.arguments[0] === node
3639
)
40+
|| (
41+
node.parent.type === 'TSLiteralType'
42+
&& node.parent.literal === node
43+
&& node.parent.parent.type === 'TSImportType'
44+
&& node.parent.parent.argument === node.parent
45+
)
3746
)) {
3847
return;
3948
}

test/prefer-node-protocol.js

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -132,3 +132,34 @@ test.babel({
132132
},
133133
],
134134
});
135+
136+
test.typescript({
137+
valid: [
138+
'const fs = require("node:fs") as "fs";',
139+
'type fs = typeof import("node:fs");',
140+
'type fs = typeof SomeType<"fs">;',
141+
'type fs = typeof fs;',
142+
],
143+
invalid: [
144+
{
145+
code: 'const fs = require("fs") as typeof import("fs");',
146+
output: 'const fs = require("node:fs") as typeof import("node:fs");',
147+
errors: 2,
148+
},
149+
{
150+
code: 'type fs = import("fs");',
151+
output: 'type fs = import("node:fs");',
152+
errors: 1,
153+
},
154+
{
155+
code: 'type fs = import("fs").fs<"fs">',
156+
output: 'type fs = import("node:fs").fs<"fs">',
157+
errors: 1,
158+
},
159+
{
160+
code: 'const fs = someFunc() as SomeType<typeof import("fs")>;',
161+
output: 'const fs = someFunc() as SomeType<typeof import("node:fs")>;',
162+
errors: 1,
163+
},
164+
],
165+
});

0 commit comments

Comments
 (0)