From 07e5c27d535fd078b383e8becd162d5de3245c7d Mon Sep 17 00:00:00 2001 From: Daniel Perez Alvarez Date: Mon, 2 Sep 2024 13:27:47 -0400 Subject: [PATCH] refactor: remove anys --- eslint.config.mjs | 6 ---- src/harmony/harmony-factory.ts | 3 +- src/harmony/utils.ts | 8 ++--- src/harmony/versions/four-seven.ts | 6 ++-- src/harmony/versions/three-eight.ts | 9 +++-- src/utils/elide-import-export.ts | 6 ++-- src/utils/ts-helpers.ts | 7 ++-- test/tests/nx.test.ts | 11 +++--- test/tests/register.test.ts | 22 ++++++++---- test/tests/transformer/general.test.ts | 6 ++-- test/tests/transformer/specific.test.ts | 13 +++++-- test/utils/helpers.ts | 48 ++++++++++++++++--------- 12 files changed, 91 insertions(+), 54 deletions(-) diff --git a/eslint.config.mjs b/eslint.config.mjs index c3a61961..b0b69497 100644 --- a/eslint.config.mjs +++ b/eslint.config.mjs @@ -24,10 +24,4 @@ export default [ "@typescript-eslint/no-require-imports": "off", }, }, - { - rules: { - // fix these warnings - "@typescript-eslint/no-explicit-any": "warn", - }, - }, ]; diff --git a/src/harmony/harmony-factory.ts b/src/harmony/harmony-factory.ts index 6fa4b8a3..1b002762 100644 --- a/src/harmony/harmony-factory.ts +++ b/src/harmony/harmony-factory.ts @@ -23,7 +23,8 @@ export function createHarmonyFactory(context: TsTransformPathsContext): HarmonyF } else if (TsFourSeven.predicate(context)) { return TsFourSeven.handler(context, prop); } else { - return (target)[prop]; + // @ts-expect-error TS(7053) FIXME: Element implicitly has an 'any' type because expression of type 'string | symbol' can't be used to index type 'typeof import("typescript") | NodeFactory'. + return target[prop]; } }, }) as HarmonyFactory; diff --git a/src/harmony/utils.ts b/src/harmony/utils.ts index 48c15a4a..2f0cb8e3 100644 --- a/src/harmony/utils.ts +++ b/src/harmony/utils.ts @@ -4,8 +4,8 @@ // @formatter:off // @prettier-ignore -export type DownSampleTsTypes = { - [i in keyof Tuple]: Tuple[i] extends any[] +export type DownSampleTsTypes = { + [i in keyof Tuple]: Tuple[i] extends unknown[] ? DownSampleTsTypes : DownSampleTsType; } & { @@ -13,8 +13,8 @@ export type DownSampleTsTypes = - T extends Exclude ? Extract[1] : T; +type DownSampleTsType = + T extends Exclude ? Extract[1] : T; // @formatter:on // endregion diff --git a/src/harmony/versions/four-seven.ts b/src/harmony/versions/four-seven.ts index c0a7e38f..b09638da 100644 --- a/src/harmony/versions/four-seven.ts +++ b/src/harmony/versions/four-seven.ts @@ -111,13 +111,15 @@ export function handler(context: TsTransformPathsContext, prop: string | symbol) }; } default: { - return (...args: any) => (factory)[prop](...args); + // @ts-expect-error TS(7019) FIXME: Rest parameter 'args' implicitly has an 'any[]' type. + return (...args) => factory[prop](...args); } } } export function downSample(...args: T): DownSampleTsTypes { - return args; + // @ts-expect-error TS(2322) FIXME: Type 'T' is not assignable to type 'DownSampleTsTypes'. + return args; } // endregion diff --git a/src/harmony/versions/three-eight.ts b/src/harmony/versions/three-eight.ts index cff317b1..e9e615eb 100644 --- a/src/harmony/versions/three-eight.ts +++ b/src/harmony/versions/three-eight.ts @@ -66,7 +66,8 @@ export function handler(context: TsTransformPathsContext, prop: string | symbol) switch (prop) { case "updateCallExpression": { - return (...args: any) => ts.updateCall.apply(void 0, args); + // @ts-expect-error TS(7019) FIXME: Rest parameter 'args' implicitly has an 'any[]' type. + return (...args) => ts.updateCall.apply(void 0, args); } case "updateImportClause": { return function ( @@ -143,13 +144,15 @@ export function handler(context: TsTransformPathsContext, prop: string | symbol) }; } default: { - return (...args: any) => (ts)[prop](...args); + // @ts-expect-error TS(7019) FIXME: Rest parameter 'args' implicitly has an 'any[]' type. + return (...args) => ts[prop](...args); } } } export function downSample(...args: T): DownSampleTsTypes { - return args; + // @ts-expect-error TS(2322) FIXME: Type 'T' is not assignable to type 'DownSampleTsTypes'. + return args; } // endregion diff --git a/src/utils/elide-import-export.ts b/src/utils/elide-import-export.ts index 441e2559..57a0a505 100755 --- a/src/utils/elide-import-export.ts +++ b/src/utils/elide-import-export.ts @@ -117,7 +117,8 @@ export function elideImportOrExportDeclaration( importClause, newModuleSpecifier, // This will be changed in the next release of TypeScript, but by that point we can drop elision entirely - (node as any).attributes || node.assertClause, + // @ts-expect-error TS(2339) FIXME: Property 'attributes' does not exist on type 'ImportDeclaration'. + node.attributes || node.assertClause, ); else return undefined; } else { @@ -150,7 +151,8 @@ export function elideImportOrExportDeclaration( exportClause, newModuleSpecifier, // This will be changed in the next release of TypeScript, but by that point we can drop elision entirely - (node as any).attributes || node.assertClause, + // @ts-expect-error TS(2339) FIXME: Property 'attributes' does not exist on type 'ExportDeclaration'. + node.attributes || node.assertClause, ) : undefined; } diff --git a/src/utils/ts-helpers.ts b/src/utils/ts-helpers.ts index 9dae038e..a11a66da 100755 --- a/src/utils/ts-helpers.ts +++ b/src/utils/ts-helpers.ts @@ -68,7 +68,7 @@ export function createSyntheticEmitHost( !tsInstance.sys.useCaseSensitiveFileNames, ), getCanonicalFileName, - } as unknown as ts.EmitHost; + } as ts.EmitHost; } /** Get ts-node register info */ @@ -86,9 +86,8 @@ export function getTsNodeRegistrationProperties(tsInstance: typeof ts) { const { config, options } = global.process[tsNodeSymbol]!; const { configFilePath } = config.options; - const pcl = configFilePath - ? tsInstance.getParsedCommandLineOfConfigFile(configFilePath, {}, tsInstance.sys) - : void 0; + // @ts-expect-error TS(2345) FIXME: Argument of type 'System' is not assignable to parameter of type 'ParseConfigFileHost'. + const pcl = configFilePath ? tsInstance.getParsedCommandLineOfConfigFile(configFilePath, {}, tsInstance.sys) : void 0; const fileNames = pcl?.fileNames || config.fileNames; const compilerOptions = Object.assign({}, config.options, options.compilerOptions, { outDir: pcl?.options.outDir }); diff --git a/test/tests/nx.test.ts b/test/tests/nx.test.ts index cdfaba1e..a027faea 100644 --- a/test/tests/nx.test.ts +++ b/test/tests/nx.test.ts @@ -17,10 +17,11 @@ describe(`NX Transformer`, () => { describe("Plugin", () => { let mockedTransformer: jest.SpyInstance; - const program: any = { x: 1 }; + const program = { x: 1 }; beforeAll(async () => { - mockedTransformer = jest.spyOn(transformerModule, "default").mockReturnValue((() => {})); + // @ts-expect-error TS(2345) FIXME: Argument of type '() => void' is not assignable to parameter of type '(transformationContext: TransformationContext) => (sourceFile: SourceFile) => SourceFile'. + mockedTransformer = jest.spyOn(transformerModule, "default").mockReturnValue(() => {}); }); afterAll(() => { mockedTransformer.mockClear(); @@ -30,8 +31,9 @@ describe(`NX Transformer`, () => { }); test(`Before properly routes transform`, () => { - const config: any = { a: 2 }; + const config = { a: 2 }; + // @ts-expect-error TS(2559) FIXME: Type '{ a: number; }' has no properties in common with type 'Omit'. nxTransformerPlugin.before(config, program); expect(mockedTransformer).toHaveBeenCalledTimes(1); @@ -43,8 +45,9 @@ describe(`NX Transformer`, () => { }); test(`After properly routes transform`, () => { - const config: any = { a: 2, afterDeclarations: true }; + const config = { a: 2, afterDeclarations: true }; + // @ts-expect-error TS(2345) FIXME: Argument of type '{ x: number; }' is not assignable to parameter of type 'Program'. nxTransformerPlugin.afterDeclarations(config, program); expect(mockedTransformer).toHaveBeenCalledTimes(1); diff --git a/test/tests/register.test.ts b/test/tests/register.test.ts index 5f616fe5..356f4f43 100755 --- a/test/tests/register.test.ts +++ b/test/tests/register.test.ts @@ -26,8 +26,10 @@ const configMap = Object.entries(configs).map(([label, cfg]) => { let hasAfterDeclarations: boolean = false; const transformers = [ ...[cfg].flat().map((c) => { - if ((c).before || !(c).afterDeclarations) hasBefore = true; - if ((c).afterDeclarations) hasAfterDeclarations = true; + // @ts-expect-error TS(2339) FIXME: Property 'before' does not exist on type '{} | { readonly before: true; } | { readonly afterDeclarations: true; } | {} | { readonly afterDeclarations: true; } | { readonly before: true; } | { readonly afterDeclarations: true; }'. + if (c.before || !c.afterDeclarations) hasBefore = true; + // @ts-expect-error TS(2339) FIXME: Property 'afterDeclarations' does not exist on type '{} | { readonly before: true; } | { readonly afterDeclarations: true; } | {} | { readonly afterDeclarations: true; } | { readonly before: true; } | { readonly afterDeclarations: true; }'. + if (c.afterDeclarations) hasAfterDeclarations = true; return { transform: "typescript-transform-paths", ...c, ...pluginOptions } as PluginConfig; }), otherTransformer, @@ -63,9 +65,10 @@ describe(`Register script`, () => { } }); test(`Uses existing ts-node if found`, () => { - const fakeInstance: any = {}; + const fakeInstance: unknown = {}; const originalTsNodeInstance = global.process[instanceSymbol]; + // @ts-expect-error TS(2322) FIXME: Type 'unknown' is not assignable to type 'Service | undefined'. global.process[instanceSymbol] = fakeInstance; let registerSpy: jest.SpyInstance | undefined; try { @@ -128,15 +131,17 @@ describe(`Register script`, () => { "Existing Transformer Config Factory", "No Existing Transformers", ] as const)(`%s`, (configKind) => { - const fakeExistingTransformer = function fakeExistingTransformer(): any {}; - const fakeTransformer = function fakeTransformer(): any {}; + // @ts-expect-error TS(2355) FIXME: A function whose declared type is neither 'undefined', 'void', nor 'any' must return a value. + const fakeExistingTransformer = function fakeExistingTransformer(): unknown {}; + // @ts-expect-error TS(2355) FIXME: A function whose declared type is neither 'undefined', 'void', nor 'any' must return a value. + const fakeTransformer = function fakeTransformer(): unknown {}; const fakeTransformerConfig = { before: [fakeExistingTransformer], after: [fakeExistingTransformer], afterDeclarations: [fakeExistingTransformer], }; const transformerFactoryFn = jest.fn().mockReturnValue(fakeTransformerConfig); - const fakeProgram: any = {}; + const fakeProgram: unknown = {}; let existingTransformers: CustomTransformers | ((p: Program) => CustomTransformers) | undefined; switch (configKind) { @@ -145,6 +150,7 @@ describe(`Register script`, () => { break; } case "Existing Transformer Config": { + // @ts-expect-error TS(2322) FIXME: Type '{ before: (() => unknown)[]; after: (() => unknown)[]; afterDeclarations: (() => unknown)[]; }' is not assignable to type 'CustomTransformers | ((p: Program) => CustomTransformers) | undefined'. existingTransformers = { ...fakeTransformerConfig }; break; } @@ -161,6 +167,7 @@ describe(`Register script`, () => { let mergedTransformers: CustomTransformers; beforeAll(() => { + // @ts-expect-error TS(2345) FIXME: Argument of type '() => unknown' is not assignable to parameter of type '(transformationContext: TransformationContext) => (sourceFile: SourceFile) => SourceFile'. mockTransformer = jest.spyOn(transformerModule, "default").mockReturnValue(fakeTransformer); global.process[instanceSymbol] = void 0; @@ -183,7 +190,8 @@ describe(`Register script`, () => { mergedTransformers = typeof registerResult.transformers === "function" - ? registerResult.transformers(fakeProgram) + ? // @ts-expect-error TS(2345) FIXME: Argument of type 'unknown' is not assignable to parameter of type 'Program'. + registerResult.transformers(fakeProgram) : registerResult.transformers!; }); afterAll(() => { diff --git a/test/tests/transformer/general.test.ts b/test/tests/transformer/general.test.ts index 4c1f67eb..3f987961 100755 --- a/test/tests/transformer/general.test.ts +++ b/test/tests/transformer/general.test.ts @@ -50,8 +50,10 @@ describe(`Transformer -> General Tests`, () => { beforeAll(() => { transformed = transformedFiles[file]; expected = { - js: getExpected(tsInstance, file, originalFiles[file].js, projectRoot), - dts: getExpected(tsInstance, file, originalFiles[file].dts, projectRoot), + // @ts-expect-error TS(2345) FIXME: Argument of type 'typeof ts | typeof ts | typeof import("typescript")' is not assignable to parameter of type 'typeof import("typescript")'. + js: getExpected(tsInstance, file, originalFiles[file].js, projectRoot), + // @ts-expect-error TS(2345) FIXME: Argument of type 'typeof ts | typeof ts | typeof import("typescript")' is not assignable to parameter of type 'typeof import("typescript")'. + dts: getExpected(tsInstance, file, originalFiles[file].dts, projectRoot), }; }); diff --git a/test/tests/transformer/specific.test.ts b/test/tests/transformer/specific.test.ts index e787407c..91a3565b 100755 --- a/test/tests/transformer/specific.test.ts +++ b/test/tests/transformer/specific.test.ts @@ -19,7 +19,7 @@ const baseConfig: TsTransformPathsConfig = { exclude: ["**/excluded/**", "exclud /* Test Mapping */ const modes = ["program", "manual", "ts-node"] as const; -const testConfigs: { label: string; tsInstance: any; mode: (typeof modes)[number]; tsSpecifier: string }[] = []; +const testConfigs: { label: string; tsInstance: unknown; mode: (typeof modes)[number]; tsSpecifier: string }[] = []; for (const cfg of tsModules) testConfigs.push(...modes.map((mode) => ({ label: cfg[0], tsInstance: cfg[1], mode, tsSpecifier: cfg[2] }))); @@ -53,6 +53,7 @@ declare global { describe(`Specific Tests`, () => { describe.each(testConfigs)(`TypeScript $label - Mode: $mode`, ({ tsInstance, mode, tsSpecifier }) => { + // @ts-expect-error TS(18046) FIXME: 'tsInstance' is of type 'unknown'. const tsVersion = +tsInstance.versionMajorMinor.split(".").slice(0, 2).join(""); let normalEmit: EmittedFiles; let rootDirsEmit: EmittedFiles; @@ -62,6 +63,7 @@ describe(`Specific Tests`, () => { switch (mode) { case "program": { const program = createTsProgram({ + // @ts-expect-error TS(2322) FIXME: Type 'unknown' is not assignable to type 'typeof import("typescript")'. tsInstance, tsConfigFile, pluginOptions: { @@ -72,6 +74,7 @@ describe(`Specific Tests`, () => { normalEmit = getEmitResultFromProgram(program); const rootDirsProgram = createTsProgram({ + // @ts-expect-error TS(2322) FIXME: Type 'unknown' is not assignable to type 'typeof import("typescript")'. tsInstance, tsConfigFile, pluginOptions: { @@ -84,20 +87,24 @@ describe(`Specific Tests`, () => { } case "manual": { skipDts = true; + // @ts-expect-error TS(18046) FIXME: 'tsInstance' is of type 'unknown'. const pcl = tsInstance.getParsedCommandLineOfConfigFile( tsConfigFile, {}, - tsInstance.sys, + // @ts-expect-error TS(18046) FIXME: 'tsInstance' is of type 'unknown'. + tsInstance.sys, )! as TS.ParsedCommandLine; normalEmit = getManualEmitResult({ ...baseConfig, useRootDirs: false }, tsInstance, pcl); rootDirsEmit = getManualEmitResult({ ...baseConfig, useRootDirs: true }, tsInstance, pcl); break; } case "ts-node": { + // @ts-expect-error TS(18046) FIXME: 'tsInstance' is of type 'unknown'. const pcl = tsInstance.getParsedCommandLineOfConfigFile( tsConfigFile, {}, - tsInstance.sys, + // @ts-expect-error TS(18046) FIXME: 'tsInstance' is of type 'unknown'. + tsInstance.sys, )! as TS.ParsedCommandLine; skipDts = true; normalEmit = getTsNodeEmitResult({ ...baseConfig, useRootDirs: false }, pcl, tsSpecifier); diff --git a/test/utils/helpers.ts b/test/utils/helpers.ts index d93db331..8f57e392 100755 --- a/test/utils/helpers.ts +++ b/test/utils/helpers.ts @@ -36,7 +36,7 @@ function createWriteFile(outputFiles: EmittedFiles) { if (!ext) return; rootName = `${rootName}.ts`; const key = ext.replace(".", "") as keyof EmittedFiles[string]; - if (!outputFiles[rootName]) outputFiles[rootName] = {}; + outputFiles[rootName] ??= {} as EmittedFiles[string]; outputFiles[rootName][key] = data; }; } @@ -94,27 +94,28 @@ export function createTsProgram( let host: ts.CompilerHost | undefined; if (opt.tsConfigFile) { - const pcl = tsInstance.getParsedCommandLineOfConfigFile(opt.tsConfigFile, extendOptions, tsInstance.sys)!; + // @ts-expect-error TS(2345) FIXME: Argument of type 'System' is not assignable to parameter of type 'ParseConfigFileHost'. + const pcl = tsInstance.getParsedCommandLineOfConfigFile(opt.tsConfigFile, extendOptions, tsInstance.sys)!; compilerOptions = pcl.options; fileNames = pcl.fileNames; } else { - const files = Object.entries(compilerOptions.files!).reduce( - (p, [fileName, data]) => { - p[tsInstance.normalizePath(fileName)] = data; - return p; - }, - {}, - ); + const files = Object.entries(compilerOptions.files!).reduce((p, [fileName, data]) => { + // @ts-expect-error TS(7053) FIXME: Element implicitly has an 'any' type because expression of type 'string' can't be used to index type '{}'. + p[tsInstance.normalizePath(fileName)] = data; + return p; + }, {}); fileNames = Object.keys(files); host = tsInstance.createCompilerHost(compilerOptions); compilerOptions = extendOptions; /* Patch host to feed mock files */ - const originalGetSourceFile: any = host.getSourceFile; + const originalGetSourceFile: unknown = host.getSourceFile; host.getSourceFile = function (fileName: string, scriptTarget: ts.ScriptTarget, ...rest) { if (Object.keys(files).includes(fileName)) + // @ts-expect-error TS(7053) FIXME: Element implicitly has an 'any' type because expression of type 'string' can't be used to index type '{}'. return tsInstance.createSourceFile(fileName, files[fileName], scriptTarget); + // @ts-expect-error TS(18046) FIXME: 'originalGetSourceFile' is of type 'unknown'. else originalGetSourceFile(fileName, scriptTarget, ...rest); }; } @@ -153,22 +154,34 @@ export function getEmitResultFromProgram(program: ts.Program): EmittedFiles { return outputFiles; } -export function getManualEmitResult(pluginConfig: TsTransformPathsConfig, tsInstance: any, pcl: ts.ParsedCommandLine) { +export function getManualEmitResult( + pluginConfig: TsTransformPathsConfig, + tsInstance: unknown, + pcl: ts.ParsedCommandLine, +) { const { options: compilerOptions, fileNames } = pcl; - const transformer = tstpTransform(void 0, pluginConfig, { ts: tsInstance } as any, { compilerOptions, fileNames }); + // @ts-expect-error TS(2345) FIXME: Argument of type 'unknown' is not assignable to parameter of type 'TransformerExtras | undefined'. + const transformer = tstpTransform(void 0, pluginConfig, { ts: tsInstance } as unknown, { + compilerOptions, + fileNames, + }); + // @ts-expect-error TS(18046) FIXME: 'tsInstance' is of type 'unknown'. const { transformed } = tsInstance.transform( fileNames.map((f) => + // @ts-expect-error TS(18046) FIXME: 'tsInstance' is of type 'unknown'. tsInstance.createSourceFile(f, fs.readFileSync(f, "utf8"), tsInstance.ScriptTarget.ESNext, true), ), [transformer], compilerOptions, ); + // @ts-expect-error TS(18046) FIXME: 'tsInstance' is of type 'unknown'. const printer = tsInstance.createPrinter(); const res: EmittedFiles = {}; - for (const sourceFile of transformed) res[sourceFile.fileName] = { js: printer.printFile(sourceFile) }; + // @ts-expect-error TS(2322) FIXME: Type 'unknown' is not assignable to type '{ js: string; dts: string; }'. + for (const sourceFile of transformed) res[sourceFile.fileName] = { js: printer.printFile(sourceFile) }; return res; } @@ -181,8 +194,9 @@ export function getTsNodeEmitResult( const compiler = tsNode.create({ transpileOnly: true, transformers: { + // @ts-expect-error TS(2345) FIXME: Argument of type 'unknown' is not assignable to parameter of type 'TransformerExtras | undefined'. // eslint-disable-next-line @typescript-eslint/no-require-imports - before: [tstpTransform(void 0, pluginConfig, { ts: require(tsSpecifier) })], + before: [tstpTransform(void 0, pluginConfig, { ts: require(tsSpecifier) })], }, project: pcl.options.configFilePath, compiler: tsSpecifier, @@ -194,8 +208,10 @@ export function getTsNodeEmitResult( global.process[tsNode.REGISTER_INSTANCE] = compiler; try { const res: EmittedFiles = {}; - for (const fileName of pcl.fileNames.filter((f) => !/\.d\.ts$/.test(f))) - res[fileName] = { js: compiler.compile(fs.readFileSync(fileName, "utf8"), fileName) }; + for (const fileName of pcl.fileNames.filter((f) => !/\.d\.ts$/.test(f))) { + // @ts-expect-error TS(2322) FIXME: Type 'unknown' is not assignable to type '{ js: string; dts: string; }'. + res[fileName] = { js: compiler.compile(fs.readFileSync(fileName, "utf8"), fileName) }; + } return res; } finally {