Skip to content

Commit 67a3d0f

Browse files
refactor: replace unknown and EXPECTED_ANY with precise types across lib (#22742)
* refactor: replace unknown with precise types across lib Type the JS syntax parser, printer, scope analyzer, CSS and HTML parsers, HMR runtimes and other modules without unknown. Brace-type unknown in lib/ goes from 416 to 32, EXPECTED_ANY from 180 to 169. * refactor: type more public and internal values precisely Second pass on remaining EXPECTED_ANY and unknown: printer public types, profiling hook wrappers, loader entries, serializer tuple bounds, AST walks and plugin options. EXPECTED_ANY in lib/ 169 -> 118, unknown 32 -> 21. * chore: shorten the changeset to 80 characters
1 parent 986efee commit 67a3d0f

52 files changed

Lines changed: 1193 additions & 993 deletions

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

‎.changeset/400-precise-public-types.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,4 +2,4 @@
22
"webpack": patch
33
---
44

5-
Replace `any` with precise types in stats, serializer and dependency typings.
5+
Replace `any` and `unknown` in stats, serializer, parser and runtime types.

‎lib/Compilation.js‎

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -189,6 +189,7 @@ const { toError } = ErrorHelpers;
189189
* @import {
190190
* StatsAsset,
191191
* StatsError,
192+
* StatsJsonValue,
192193
* StatsModule
193194
* } from "./stats/DefaultStatsFactoryPlugin"
194195
*/
@@ -527,7 +528,7 @@ const { toError } = ErrorHelpers;
527528
* @property {false | "none" | "error" | "warn" | "info" | "log" | "verbose"} logging
528529
* @property {((value: string) => boolean)[]} loggingDebug
529530
* @property {boolean} loggingTrace
530-
* @property {EXPECTED_ANY} _env
531+
* @property {StatsJsonValue} _env
531532
*/
532533

533534
/** @typedef {KnownNormalizedStatsOptions & Omit<StatsOptions, keyof KnownNormalizedStatsOptions> & Record<string, EXPECTED_ANY>} NormalizedStatsOptions */
@@ -909,7 +910,11 @@ BREAKING CHANGE: Asset processing hooks in Compilation has been merged into a si
909910
processAssetsHook.tapAsync(
910911
getOptions(options),
911912
(assets, callback) =>
912-
/** @type {EXPECTED_ANY} */ (fn)(...getArgs(), callback)
913+
/** @type {(...args: [...AsArray<T>, typeof callback]) => void} */ (
914+
/** @type {typeof fn | ((...args: [...AsArray<T>, typeof callback]) => void)} */ (
915+
fn
916+
)
917+
)(...getArgs(), callback)
913918
);
914919
},
915920
/** @type {AsyncSeriesHook<T>["tapPromise"]} */

‎lib/asset/WebManifestParser.js‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -121,8 +121,8 @@ class WebManifestParser extends Parser {
121121
if (!buildHttp && ABSOLUTE_URL_SCHEME_REGEXP.test(url)) continue;
122122
// acorn offsets are into `(${source})`; the leading `(` and the
123123
// opening quote cancel, so the inner span is [start, end - 2].
124-
const { start, end } = /** @type {Positioned} */ (
125-
/** @type {unknown} */ (value)
124+
const { start, end } = /** @type {Expression & Positioned} */ (
125+
value
126126
);
127127
const dep = new HtmlSourceDependency(url, [
128128
toSourceOffset(start),

‎lib/config/cli.js‎

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -229,8 +229,10 @@ const getArguments = (schema = webpackSchema) => {
229229
description: undefined,
230230
simpleType:
231231
/** @type {SimpleType} */
232-
(/** @type {unknown} */ (undefined)),
233-
multiple: /** @type {boolean} */ (/** @type {unknown} */ (undefined))
232+
(/** @type {SimpleType | undefined} */ (undefined)),
233+
multiple: /** @type {boolean} */ (
234+
/** @type {boolean | undefined} */ (undefined)
235+
)
234236
};
235237
};
236238

@@ -278,8 +280,10 @@ const getArguments = (schema = webpackSchema) => {
278280
description: undefined,
279281
simpleType:
280282
/** @type {SimpleType} */
281-
(/** @type {unknown} */ (undefined)),
282-
multiple: /** @type {boolean} */ (/** @type {unknown} */ (undefined))
283+
(/** @type {SimpleType | undefined} */ (undefined)),
284+
multiple: /** @type {boolean} */ (
285+
/** @type {boolean | undefined} */ (undefined)
286+
)
283287
};
284288
}
285289

‎lib/config/defaults.js‎

Lines changed: 21 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -87,6 +87,8 @@ const {
8787
*/
8888
/** @import { WasmLoadingTypes } from "../wasm/EnableWasmLoadingPlugin" */
8989
/** @import { PlatformTargetProperties, TargetProperties } from "./target" */
90+
/** @import Compiler from "../Compiler" */
91+
/** @typedef {Parameters<import("minimizer-webpack-plugin")["apply"]>[0]} MinimizerCompiler */
9092

9193
/**
9294
* Defines the recursive non nullable type used by this module.
@@ -286,11 +288,13 @@ const A = (obj, prop, factory) => {
286288
if (item === "...") {
287289
if (newArray === undefined) {
288290
newArray = value.slice(0, i);
289-
obj[prop] = /** @type {T[P]} */ (/** @type {unknown} */ (newArray));
291+
obj[prop] = /** @type {T[P]} */ (
292+
/** @type {T[P] | NonNullable<typeof newArray>} */ (newArray)
293+
);
290294
}
291295
const items =
292-
/** @type {(T[P] extends (infer E)[] ? E : never)[]} */
293-
(/** @type {unknown} */ (factory()));
296+
/** @type {NonNullable<typeof newArray>} */
297+
(/** @type {T[P] | NonNullable<typeof newArray>} */ (factory()));
294298
if (items !== undefined) {
295299
for (const item of items) {
296300
newArray.push(item);
@@ -2498,9 +2502,10 @@ const applyOptimizationDefaults = (
24982502
D(optimization, "realContentHash", production);
24992503
// A plugin assigning the object shorthand in `apply()` runs after
25002504
// normalization: it replaces `minimizeOptions`, keeping `minimize` boolean.
2501-
const minimizeAssignedInApply = /** @type {unknown} */ (
2502-
optimization.minimize
2503-
);
2505+
const minimizeAssignedInApply =
2506+
/** @type {Optimization["minimize"] | OptimizationMinimizeOptions} */ (
2507+
optimization.minimize
2508+
);
25042509
if (typeof minimizeAssignedInApply === "object") {
25052510
optimization.minimizeOptions = /** @type {OptimizationMinimizeOptions} */ (
25062511
minimizeAssignedInApply
@@ -2613,7 +2618,11 @@ const applyOptimizationDefaults = (
26132618
test: assetNameTest(["[cm]?js"]),
26142619
minify: javascriptMinify,
26152620
minimizerOptions: javascriptOptions
2616-
}).apply(/** @type {EXPECTED_ANY} */ (compiler));
2621+
}).apply(
2622+
/** @type {MinimizerCompiler} */ (
2623+
/** @type {Compiler | MinimizerCompiler} */ (compiler)
2624+
)
2625+
);
26172626
return;
26182627
}
26192628
/** @type {(typeof javascriptMinify | string)[]} */
@@ -2703,7 +2712,11 @@ const applyOptimizationDefaults = (
27032712
test: assetNameTest(extensions),
27042713
minify,
27052714
minimizerOptions
2706-
}).apply(/** @type {EXPECTED_ANY} */ (compiler));
2715+
}).apply(
2716+
/** @type {MinimizerCompiler} */ (
2717+
/** @type {Compiler | MinimizerCompiler} */ (compiler)
2718+
)
2719+
);
27072720
}
27082721
}
27092722
]);

‎lib/config/getClaimedAssetTypes.js‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -9,10 +9,10 @@ const { matchObject } = require("../devtool/ModuleFilenameHelpers");
99

1010
/** @import Compiler from "../Compiler" */
1111
/** @import { MatchObject } from "../devtool/ModuleFilenameHelpers" */
12-
/** @typedef {MatchObject & { minimizer?: import("minimizer-webpack-plugin").InternalPluginOptions<EXPECTED_ANY>["minimizer"] }} MinimizerOptions */
12+
/** @typedef {MatchObject & { minimizer?: import("minimizer-webpack-plugin").InternalPluginOptions<import("terser").MinifyOptions>["minimizer"] }} MinimizerOptions */
1313

1414
/**
15-
* @param {unknown} candidate a configured plugin or minimizer entry
15+
* @param {NonNullable<Compiler["options"]["optimization"]["minimizer"]>[number] | Compiler["options"]["plugins"][number]} candidate a configured plugin or minimizer entry
1616
* @param {string} file probe filename
1717
* @returns {boolean} whether the candidate minimizes that file
1818
*/

‎lib/css/CssModulesPlugin.js‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -567,7 +567,7 @@ class CssModulesPlugin {
567567
return new CssModule(
568568
/** @type {CssModuleCreateData} */
569569
(
570-
/** @type {unknown} */ ({
570+
/** @type {Partial<CssModuleCreateData>} */ ({
571571
...createData,
572572
exportType
573573
})

‎lib/css/syntax-parser.js‎

Lines changed: 29 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -1790,21 +1790,21 @@ const _NO_SKIP_TYPES = new Uint8Array(32);
17901790
// rules, the common case. Every consumer reads these lists read-only, so one
17911791
// instance replaces an empty array per rule, and freezing makes a push fail.
17921792
const _EMPTY_LIST = /** @type {Rule[]} */ (
1793-
/** @type {unknown} */ (Object.freeze([]))
1793+
/** @type {Rule[] | ReadonlyArray<never>} */ (Object.freeze([]))
17941794
);
17951795
// `consumeABlock`'s and `consumeABlocksContentsInto`'s results, written instead
17961796
// of returned — see there. Read them immediately; the next block overwrites them.
17971797
/** @type {Declaration[]} */
17981798
let _blockDecls = /** @type {Declaration[]} */ (
1799-
/** @type {unknown} */ (_EMPTY_LIST)
1799+
/** @type {Declaration[] | Rule[]} */ (_EMPTY_LIST)
18001800
);
18011801
/** @type {Rule[]} */
18021802
let _blockRules = _EMPTY_LIST;
18031803
let _blockStart = 0;
18041804
let _blockEnd = 0;
18051805
/** @type {Declaration[]} */
18061806
let _bcDecls = /** @type {Declaration[]} */ (
1807-
/** @type {unknown} */ (_EMPTY_LIST)
1807+
/** @type {Declaration[] | Rule[]} */ (_EMPTY_LIST)
18081808
);
18091809
/** @type {Rule[]} */
18101810
let _bcRules = _EMPTY_LIST;
@@ -1888,17 +1888,20 @@ let _declBodies = [];
18881888
/** @type {Node[][]} */
18891889
let _ruleBodies = [];
18901890

1891-
let _locConverter = /** @type {LocConverter} */ (/** @type {unknown} */ (null));
1891+
let _locConverter = /** @type {LocConverter} */ (
1892+
/** @type {LocConverter | null} */ (null)
1893+
);
18921894
// The caller's input before §3.3 replaced its NULs, the same length, which
18931895
// `A.source` slices so a node reads exactly as written.
18941896
let _originalInput = "";
18951897

18961898
// Node refs are integers here but typed `Node` across the parser; these are
18971899
// identity casts that just satisfy the type system at the boundary.
18981900
/** @type {(n: Node) => number} */
1899-
const _nodeIndex = (n) => /** @type {number} */ (/** @type {unknown} */ (n));
1901+
const _nodeIndex = (n) =>
1902+
/** @type {number} */ (/** @type {number | Node} */ (n));
19001903
/** @type {(i: number) => Node} */
1901-
const _nodeRef = (i) => /** @type {Node} */ (/** @type {unknown} */ (i));
1904+
const _nodeRef = (i) => /** @type {Node} */ (/** @type {Node | number} */ (i));
19021905

19031906
/** @param {number} need minimum capacity */
19041907
const _grow = (need) => {
@@ -2583,7 +2586,7 @@ const normalizeIntoTokenStream = (input, pos, onComment) => {
25832586
// Shared frozen empty list for a block body with no declarations / child rules,
25842587
// so equal-empty reads return one reference (mirrors `_EMPTY_LIST`).
25852588
const _READER_EMPTY = /** @type {Rule[]} */ (
2586-
/** @type {unknown} */ (Object.freeze([]))
2589+
/** @type {Rule[] | ReadonlyArray<never>} */ (Object.freeze([]))
25872590
);
25882591

25892592
/**
@@ -2651,7 +2654,7 @@ const _readRefList = (store, list) => {
26512654
// that reader's `_store` snapshot by `_i`. Created once rather than per store,
26522655
// so all readers share one hidden map and stay monomorphic across parses.
26532656
const NODE_READER_PROTO = /** @type {NodeReader} */ ({
2654-
_store: /** @type {NodeStore} */ (/** @type {unknown} */ (null)),
2657+
_store: /** @type {NodeStore} */ (/** @type {NodeStore | null} */ (null)),
26552658
_i: 0,
26562659
get type() {
26572660
return this._store.types[this._i];
@@ -2880,7 +2883,9 @@ const _finishStore = () => {
28802883
_ruleBodies = [];
28812884
_listPool.length = 0;
28822885
_S._input = "";
2883-
_locConverter = /** @type {LocConverter} */ (/** @type {unknown} */ (null));
2886+
_locConverter = /** @type {LocConverter} */ (
2887+
/** @type {LocConverter | null} */ (null)
2888+
);
28842889
return store;
28852890
};
28862891

@@ -3271,8 +3276,8 @@ const consumeAQualifiedRule = (ts, stopToken, nested = false) => {
32713276
// two non-whitespace tokens the `--foo: {` disambiguation below needs.
32723277
const skip = _skipSelectorPrelude;
32733278
// Non-skip: first two non-whitespace prelude nodes (computed at the `{`).
3274-
let first = /** @type {Node} */ (/** @type {unknown} */ (0));
3275-
let second = /** @type {Node} */ (/** @type {unknown} */ (0));
3279+
let first = /** @type {Node} */ (/** @type {Node | number} */ (0));
3280+
let second = /** @type {Node} */ (/** @type {Node | number} */ (0));
32763281
// Skip mode: the same two tokens tracked by token type + start, so a dropped
32773282
// leaf selector token needs no materialized node just for the disambiguation.
32783283
// `0` (no token type) = unset.
@@ -4475,7 +4480,9 @@ const TOP_LEVEL_CONSUMERS = {
44754480
// recursive call sites monomorphic and allocates no closure per parse.
44764481
/** @typedef {import("../util/SourceProcessor").CompiledVisitorBucket<CssPath>} CompiledVisitorBucket */
44774482
/** @type {CompiledVisitorMap} */
4478-
let _visitors = /** @type {CompiledVisitorMap} */ (/** @type {unknown} */ ([]));
4483+
let _visitors = /** @type {CompiledVisitorMap} */ (
4484+
/** @type {CompiledVisitorMap | never[]} */ ([])
4485+
);
44794486
let _recurseBlocks = true;
44804487
// Printing needs a faithful serialization, so it keeps dropped input as `NodeType.Raw`
44814488
// nodes; a walk-only parse leaves this false and allocates none.
@@ -5090,10 +5097,10 @@ const UNKEYED = "";
50905097
/** @type {BlockSpans[]} */
50915098
const _blockSpans = [];
50925099
const _NO_RULE_SPANS = /** @type {RuleSpan[]} */ (
5093-
/** @type {unknown} */ (Object.freeze([]))
5100+
/** @type {RuleSpan[] | ReadonlyArray<never>} */ (Object.freeze([]))
50945101
);
50955102
const _NO_BLOCK_SPANS = /** @type {BlockSpans[]} */ (
5096-
/** @type {unknown} */ (Object.freeze([]))
5103+
/** @type {BlockSpans[] | ReadonlyArray<never>} */ (Object.freeze([]))
50975104
);
50985105
/**
50995106
* @typedef {{ piece: number, text: string, spans: RuleSpan[], empties: number }} TakenPiece
@@ -8221,7 +8228,9 @@ const grammar = (input, visitors, writer, options) => {
82218228
_anonymousLayers = 0;
82228229
_S._input = "";
82238230
_originalInput = "";
8224-
_locConverter = /** @type {LocConverter} */ (/** @type {unknown} */ (null));
8231+
_locConverter = /** @type {LocConverter} */ (
8232+
/** @type {LocConverter | null} */ (null)
8233+
);
82258234
_declBodies.length = 0;
82268235
_ruleBodies.length = 0;
82278236
_flatTop = 0;
@@ -8230,7 +8239,9 @@ const grammar = (input, visitors, writer, options) => {
82308239
_flatGrowHint = _flatPeak;
82318240
_flat = EMPTY_I32;
82328241
}
8233-
_visitors = /** @type {CompiledVisitorMap} */ (/** @type {unknown} */ ([]));
8242+
_visitors = /** @type {CompiledVisitorMap} */ (
8243+
/** @type {CompiledVisitorMap | never[]} */ ([])
8244+
);
82348245
_commentBucket = undefined;
82358246
if (_capacity > _SHRINK_CAPACITY) {
82368247
// +1: node ids are 1-based and grow fires at `id >= capacity`.
@@ -11012,7 +11023,7 @@ const _resolveColor = (text) => {
1101211023
}
1101311024
// Every call that answers records them, so a non-null answer is one.
1101411025
const raw = /** @type {number[]} */ (
11015-
/** @type {unknown} */ (_fallbackChannels)
11026+
/** @type {number[] | null} */ (_fallbackChannels)
1101611027
);
1101711028
return {
1101811029
linear: raw.map((channel) => _gammaDecode(channel / 255)),
@@ -19222,7 +19233,7 @@ const _S = {
1922219233
// The walk's current position (`A.node` / `A.parent` read these; module-level
1922319234
// so the accessor methods' defaults avoid self-referential `this` typing).
1922419235
/** @type {Node} */
19225-
_currentNode: /** @type {Node} */ (/** @type {unknown} */ (0)),
19236+
_currentNode: /** @type {Node} */ (/** @type {Node | number} */ (0)),
1922619237
// The declaration `_inKeywordOnlyValue` last answered for, and its answer: one
1922719238
// value's identifiers all ask it, and the read is a pointer compare after the
1922819239
// first. Cleared with the rest of the parse state, so no node outlives it.

‎lib/debug/ProfilingPlugin.js‎

Lines changed: 23 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -34,23 +34,7 @@ const { fileUrlToPath } = require("../util/identifier");
3434
* @property {AbsolutePath=} outputPath Path to the output file e.g. `path.resolve(__dirname, 'profiling/events.json')`. Defaults to `events.json`.
3535
*/
3636

37-
/**
38-
* Defines the hook type used by this module.
39-
* @template T, R
40-
* @typedef {import("tapable").Hook<T, R>} Hook
41-
*/
42-
43-
/**
44-
* Defines the fake hook type used by this module.
45-
* @template T
46-
* @typedef {import("../util/deprecation").FakeHook<T>} FakeHook
47-
*/
48-
49-
/**
50-
* Defines the hook map type used by this module.
51-
* @template T
52-
* @typedef {import("tapable").HookMap<T>} HookMap
53-
*/
37+
/** @import { FakeHookMarker } from "../util/deprecation" */
5438

5539
/**
5640
* Defines the hook interceptor type used by this module.
@@ -408,27 +392,43 @@ class ProfilingPlugin {
408392
}
409393
}
410394

411-
/** @typedef {Record<string, Hook<EXPECTED_ANY, EXPECTED_ANY> | FakeHook<EXPECTED_ANY> | HookMap<EXPECTED_ANY>>} Hooks */
395+
/**
396+
* The part of a tapable `HookInterceptor` this plugin sets: it rewraps each tap.
397+
* @typedef {{ register?(tap: FullTap): FullTap }} TapInterceptor
398+
*/
399+
400+
/**
401+
* What intercepting a tapable `Hook` needs of it. Methods, so every hook fits
402+
* whatever its arguments, result and additional tap options.
403+
* @typedef {{ intercept(interceptor: TapInterceptor): void, _fakeHook?: undefined }} HookWithInterceptor
404+
*/
405+
406+
/**
407+
* What intercepting a tapable `HookMap` needs of it, whatever hook it holds.
408+
* @typedef {{ for(key: string): HookWithInterceptor, intercept(interceptor: { factory?(key: string, hook: HookWithInterceptor): HookWithInterceptor }): void, _fakeHook?: undefined }} HookMapWithInterceptor
409+
*/
410+
411+
/** @typedef {Record<string, HookWithInterceptor | HookMapWithInterceptor | FakeHookMarker>} Hooks */
412412

413413
/**
414414
* Intercepts the taps of a hook or every cached and future hook in a hook map.
415-
* @param {Hooks[string]} hook the hook or hook map
416-
* @param {HookInterceptor<EXPECTED_ANY, EXPECTED_ANY>} interceptor what intercepts each tap
415+
* @param {HookWithInterceptor | HookMapWithInterceptor} hook the hook or hook map
416+
* @param {TapInterceptor} interceptor what intercepts each tap
417417
* @returns {void}
418418
*/
419419
const interceptTaps = (hook, interceptor) => {
420420
if ("for" in hook) {
421421
const { _map } =
422-
/** @type {HookMap<Hook<EXPECTED_ANY, EXPECTED_ANY>> & { _map: Map<unknown, Hook<EXPECTED_ANY, EXPECTED_ANY>> }} */
422+
/** @type {HookMapWithInterceptor & { _map: Map<string, HookWithInterceptor> }} */
423423
(hook);
424424
for (const cached of _map.values()) {
425425
cached.intercept(interceptor);
426426
}
427427
hook.intercept({
428428
/**
429429
* @param {string} key the key the hook is created for
430-
* @param {Hook<EXPECTED_ANY, EXPECTED_ANY>} created the hook created
431-
* @returns {Hook<EXPECTED_ANY, EXPECTED_ANY>} the same hook, intercepted
430+
* @param {HookWithInterceptor} created the hook created
431+
* @returns {HookWithInterceptor} the same hook, intercepted
432432
*/
433433
factory: (key, created) => {
434434
created.intercept(interceptor);

‎lib/define/DefinePlugin.js‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1115,7 +1115,9 @@ class DefinePlugin {
11151115
// so scanning that text cannot find every reference.
11161116
const hasPreparsedAst =
11171117
/** @type {{ _ast: PreparsedAst | null }} */ (
1118-
/** @type {unknown} */ (module)
1118+
/** @type {NormalModule | { _ast: PreparsedAst | null }} */ (
1119+
module
1120+
)
11191121
)._ast !== null;
11201122
await resolveAsyncRuntimeValues(
11211123
compilation,

0 commit comments

Comments
 (0)