Skip to content

Commit 3f691ea

Browse files
JanpotTimer
andauthored
Remove ts-ignore where possible (#10541)
* Remove ts-ignore where possible And replace by typecasts * More accurate types * bend cliententries in a correct shape earlier on * comment becomes unnecessary * add webpack overload to allow for the next.js use case * Avoid changing public interface Co-authored-by: Joe Haddad <[email protected]>
1 parent f4c5a95 commit 3f691ea

File tree

13 files changed

+66
-35
lines changed

13 files changed

+66
-35
lines changed

packages/next/build/babel/plugins/react-loadable-plugin.ts

-2
Original file line numberDiff line numberDiff line change
@@ -85,8 +85,6 @@ export default function({ types: t }: { types: typeof BabelTypes }): PluginObj {
8585
callExpression.node.arguments.push(t.objectExpression([]))
8686
}
8787
// This is needed as the code is modified above
88-
// TODO: remove ignore statement
89-
// @ts-ignore
9088
args = callExpression.get('arguments')
9189
loader = args[0]
9290
options = args[1]

packages/next/build/compiler.ts

-1
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,6 @@ export function runCompiler(
2626
config: webpack.Configuration | webpack.Configuration[]
2727
): Promise<CompilerResult> {
2828
return new Promise(async (resolve, reject) => {
29-
// @ts-ignore webpack allows both a single config or array of configs
3029
const compiler = webpack(config)
3130
compiler.run((err: Error, statsOrMultiStats: any) => {
3231
if (err) {

packages/next/build/webpack-config.ts

+11-10
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,6 @@
11
import crypto from 'crypto'
22
import ForkTsCheckerWebpackPlugin from 'fork-ts-checker-webpack-plugin'
33
import path from 'path'
4-
// @ts-ignore: Currently missing types
54
import PnpWebpackPlugin from 'pnp-webpack-plugin'
65
import webpack from 'webpack'
76
import {
@@ -29,7 +28,6 @@ import {
2928
} from './plugins/collect-plugins'
3029
import { build as buildConfiguration } from './webpack/config'
3130
import { __overrideCssConfiguration } from './webpack/config/blocks/css/overrideCssConfiguration'
32-
// @ts-ignore: JS file
3331
import { pluginLoaderOptions } from './webpack/loaders/next-plugin-loader'
3432
import BuildManifestPlugin from './webpack/plugins/build-manifest-plugin'
3533
import ChunkNamesPlugin from './webpack/plugins/chunk-names-plugin'
@@ -113,6 +111,12 @@ function getOptimizedAliases(
113111
)
114112
}
115113

114+
type ClientEntries = {
115+
'main.js': string[]
116+
} & {
117+
[key: string]: string
118+
}
119+
116120
export default async function getBaseWebpackConfig(
117121
dir: string,
118122
{
@@ -197,7 +201,7 @@ export default async function getBaseWebpackConfig(
197201
const outputPath = path.join(distDir, isServer ? outputDir : '')
198202
const totalPages = Object.keys(entrypoints).length
199203
const clientEntries = !isServer
200-
? {
204+
? ({
201205
// Backwards compatibility
202206
'main.js': [],
203207
[CLIENT_STATIC_FILES_RUNTIME_MAIN]:
@@ -215,7 +219,7 @@ export default async function getBaseWebpackConfig(
215219
? 'polyfills-nomodule.js'
216220
: 'polyfills.js'
217221
),
218-
}
222+
} as ClientEntries)
219223
: undefined
220224

221225
let typeScriptPath
@@ -652,7 +656,6 @@ export default async function getBaseWebpackConfig(
652656
],
653657
plugins: [PnpWebpackPlugin],
654658
},
655-
// @ts-ignore this is filtered
656659
module: {
657660
rules: [
658661
{
@@ -902,8 +905,7 @@ export default async function getBaseWebpackConfig(
902905
webpack,
903906
})
904907

905-
// @ts-ignore: Property 'then' does not exist on type 'Configuration'
906-
if (typeof webpackConfig.then === 'function') {
908+
if (typeof (webpackConfig as any).then === 'function') {
907909
console.warn(
908910
'> Promise returned in next config. https://err.sh/zeit/next.js/promise-in-next-config'
909911
)
@@ -1109,7 +1111,6 @@ export default async function getBaseWebpackConfig(
11091111
// Server compilation doesn't have main.js
11101112
if (clientEntries && entry['main.js'] && entry['main.js'].length > 0) {
11111113
const originalFile = clientEntries[CLIENT_STATIC_FILES_RUNTIME_MAIN]
1112-
// @ts-ignore TODO: investigate type error
11131114
entry[CLIENT_STATIC_FILES_RUNTIME_MAIN] = [
11141115
...entry['main.js'],
11151116
originalFile,
@@ -1122,8 +1123,8 @@ export default async function getBaseWebpackConfig(
11221123
}
11231124

11241125
if (!dev) {
1125-
// @ts-ignore entry is always a function
1126-
webpackConfig.entry = await webpackConfig.entry()
1126+
// entry is always a function
1127+
webpackConfig.entry = await (webpackConfig.entry as webpack.EntryFunc)()
11271128
}
11281129

11291130
return webpackConfig

packages/next/build/webpack/plugins/webpack-conformance-plugin/index.ts

+4-3
Original file line numberDiff line numberDiff line change
@@ -88,16 +88,17 @@ export default class WebpackConformancePlugin {
8888
private parserHandler = (factory: compilation.NormalModuleFactory): void => {
8989
const JS_TYPES = ['auto', 'esm', 'dynamic']
9090
const collectedVisitors: Map<string, [NodeInspector?]> = new Map()
91-
// Collect all intereseted visitors from all tests.
91+
// Collect all interested visitors from all tests.
9292
this.tests.forEach(test => {
9393
if (test.getAstNode) {
9494
const getAstNodeCallbacks: IGetAstNodeResult[] = test.getAstNode()
9595
getAstNodeCallbacks.forEach(result => {
9696
if (!collectedVisitors.has(result.visitor)) {
9797
collectedVisitors.set(result.visitor, [])
9898
}
99-
// @ts-ignore
100-
collectedVisitors.get(result.visitor).push(result.inspectNode)
99+
;(collectedVisitors.get(result.visitor) as NodeInspector[]).push(
100+
result.inspectNode
101+
)
101102
})
102103
}
103104
})

packages/next/client/link.tsx

+1-2
Original file line numberDiff line numberDiff line change
@@ -161,8 +161,7 @@ class Link extends Component<LinkProps> {
161161
})
162162

163163
linkClicked = (e: React.MouseEvent) => {
164-
// @ts-ignore target exists on currentTarget
165-
const { nodeName, target } = e.currentTarget
164+
const { nodeName, target } = e.currentTarget as HTMLAnchorElement
166165
if (
167166
nodeName === 'A' &&
168167
((target && target !== '_self') ||

packages/next/lib/resolve-request.ts

-1
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,6 @@ export function resolveRequest(req: string, issuer: string) {
55
// The `resolve` package is prebuilt through ncc, which prevents
66
// PnP from being able to inject itself into it. To circumvent
77
// this, we simply use PnP directly when available.
8-
// @ts-ignore
98
if (process.versions.pnp) {
109
const { resolveRequest } = require(`pnpapi`)
1110
return resolveRequest(req, issuer, { considerBuiltins: false })

packages/next/lib/verifyTypeScriptSetup.ts

-1
Original file line numberDiff line numberDiff line change
@@ -123,7 +123,6 @@ export async function verifyTypeScriptSetup(
123123
}
124124

125125
const tsPath = await checkDependencies({ dir, isYarn })
126-
// @ts-ignore
127126
const ts = (await import(tsPath)) as typeof import('typescript')
128127

129128
const compilerOptions: any = {

packages/next/next-server/lib/loadable-context.ts

+1-4
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,4 @@ import * as React from 'react'
22

33
type CaptureFn = (moduleName: string) => void
44

5-
// @ts-ignore for some reason the React types don't like this, but it's correct.
6-
export const LoadableContext: React.Context<CaptureFn | null> = React.createContext(
7-
null
8-
)
5+
export const LoadableContext = React.createContext<CaptureFn | null>(null)

packages/next/next-server/lib/router/router.ts

+21-7
Original file line numberDiff line numberDiff line change
@@ -17,8 +17,8 @@ import { getRouteMatcher } from './utils/route-matcher'
1717
import { getRouteRegex } from './utils/route-regex'
1818

1919
function addBasePath(path: string): string {
20-
// @ts-ignore variable is always a string
21-
const p: string = process.env.__NEXT_ROUTER_BASEPATH
20+
// variable is always a string
21+
const p = process.env.__NEXT_ROUTER_BASEPATH as string
2222
return path.indexOf(p) !== 0 ? p + path : path
2323
}
2424

@@ -68,6 +68,8 @@ type BeforePopStateCallback = (state: any) => boolean
6868

6969
type ComponentLoadCancel = (() => void) | null
7070

71+
type HistoryMethod = 'replaceState' | 'pushState'
72+
7173
function fetchNextData(
7274
pathname: string,
7375
query: ParsedUrlQuery | null,
@@ -313,7 +315,12 @@ export default class Router implements BaseRouter {
313315
return this.change('replaceState', url, as, options)
314316
}
315317

316-
change(method: string, _url: Url, _as: Url, options: any): Promise<boolean> {
318+
change(
319+
method: HistoryMethod,
320+
_url: Url,
321+
_as: Url,
322+
options: any
323+
): Promise<boolean> {
317324
return new Promise((resolve, reject) => {
318325
if (!options._h) {
319326
this.isSsr = false
@@ -444,28 +451,35 @@ export default class Router implements BaseRouter {
444451
})
445452
}
446453

447-
changeState(method: string, url: string, as: string, options = {}): void {
454+
changeState(
455+
method: HistoryMethod,
456+
url: string,
457+
as: string,
458+
options = {}
459+
): void {
448460
if (process.env.NODE_ENV !== 'production') {
449461
if (typeof window.history === 'undefined') {
450462
console.error(`Warning: window.history is not available.`)
451463
return
452464
}
453-
// @ts-ignore method should always exist on history
465+
454466
if (typeof window.history[method] === 'undefined') {
455467
console.error(`Warning: window.history.${method} is not available`)
456468
return
457469
}
458470
}
459471

460472
if (method !== 'pushState' || getURL() !== as) {
461-
// @ts-ignore method should always exist on history
462473
window.history[method](
463474
{
464475
url,
465476
as,
466477
options,
467478
},
468-
null,
479+
// Most browsers currently ignores this parameter, although they may use it in the future.
480+
// Passing the empty string here should be safe against future changes to the method.
481+
// https://developer.mozilla.org/en-US/docs/Web/API/History/replaceState
482+
'',
469483
as
470484
)
471485
}

packages/next/next-server/server/lib/path-match.ts

+1-2
Original file line numberDiff line numberDiff line change
@@ -49,8 +49,7 @@ function decodeParam(param: string) {
4949
try {
5050
return decodeURIComponent(param)
5151
} catch (_) {
52-
const err = new Error('failed to decode param')
53-
// @ts-ignore DECODE_FAILED is handled
52+
const err: Error & { code?: string } = new Error('failed to decode param')
5453
err.code = 'DECODE_FAILED'
5554
throw err
5655
}

packages/next/next-server/server/render.tsx

+2-2
Original file line numberDiff line numberDiff line change
@@ -400,8 +400,8 @@ export async function renderToHTML(
400400

401401
await Loadable.preloadAll() // Make sure all dynamic imports are loaded
402402

403-
// @ts-ignore url will always be set
404-
const asPath: string = req.url
403+
// url will always be set
404+
const asPath = req.url as string
405405
const router = new ServerRouter(pathname, query, asPath, {
406406
isFallback: isFallback,
407407
})

packages/next/types/misc.d.ts

+21
Original file line numberDiff line numberDiff line change
@@ -91,7 +91,28 @@ declare module 'autodll-webpack-plugin' {
9191
export = AutoDllPlugin
9292
}
9393

94+
declare module 'pnp-webpack-plugin' {
95+
import webpack from 'webpack'
96+
import ForkTsCheckerWebpackPlugin from 'fork-ts-checker-webpack-plugin'
97+
98+
class PnpWebpackPlugin extends webpack.Plugin {
99+
static forkTsCheckerOptions: <
100+
T extends Partial<ForkTsCheckerWebpackPlugin.Options>
101+
>(
102+
settings: T
103+
) => T & {
104+
resolveModuleNameModule?: string
105+
resolveTypeReferenceDirectiveModule?: string
106+
}
107+
}
108+
109+
export = PnpWebpackPlugin
110+
}
111+
94112
declare module NodeJS {
113+
interface ProcessVersions {
114+
pnp?: string
115+
}
95116
interface Process {
96117
crossOrigin?: string
97118
}

packages/next/types/webpack.d.ts

+4
Original file line numberDiff line numberDiff line change
@@ -56,6 +56,10 @@ declare module 'webpack' {
5656
): webpack.MultiWatching | webpack.MultiCompiler
5757
function webpack(options: webpack.Configuration[]): webpack.MultiCompiler
5858

59+
function webpack(
60+
options: webpack.Configuration | webpack.Configuration[]
61+
): webpack.Compiler | webpack.MultiCompiler
62+
5963
namespace webpack {
6064
/** Webpack package version. */
6165
const version: string | undefined

0 commit comments

Comments
 (0)