Skip to content

Commit

Permalink
chore: get rid of some anys (#10511)
Browse files Browse the repository at this point in the history
  • Loading branch information
SimenB authored Sep 14, 2020
1 parent 621b8ea commit 7e71d5f
Show file tree
Hide file tree
Showing 65 changed files with 209 additions and 181 deletions.
20 changes: 10 additions & 10 deletions e2e/Utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import * as path from 'path';
import * as fs from 'graceful-fs';
import type {Config} from '@jest/types';
import {ExecaReturnValue, sync as spawnSync} from 'execa';
import type {PackageJson} from 'type-fest';
import rimraf = require('rimraf');
import dedent = require('dedent');
import which = require('which');
Expand Down Expand Up @@ -65,7 +66,7 @@ export const linkJestPackage = (packageName: string, cwd: Config.Path) => {

export const makeTemplate = (
str: string,
): ((values?: Array<any>) => string) => (values?: Array<any>) =>
): ((values?: Array<unknown>) => string) => (values = []) =>
str.replace(/\$(\d+)/g, (_match, number) => {
if (!Array.isArray(values)) {
throw new Error('Array of values must be passed to the template.');
Expand Down Expand Up @@ -166,19 +167,18 @@ export const sortLines = (output: string) =>
.filter(Boolean)
.join('\n');

const DEFAULT_PACKAGE_JSON: PackageJson = {
description: 'THIS IS AN AUTOGENERATED FILE AND SHOULD NOT BE ADDED TO GIT',
jest: {
testEnvironment: 'node',
},
};

export const createEmptyPackage = (
directory: Config.Path,
packageJson?: {[keys: string]: any},
packageJson = DEFAULT_PACKAGE_JSON,
) => {
const DEFAULT_PACKAGE_JSON = {
description: 'THIS IS AN AUTOGENERATED FILE AND SHOULD NOT BE ADDED TO GIT',
jest: {
testEnvironment: 'node',
},
};

fs.mkdirSync(directory, {recursive: true});
packageJson || (packageJson = DEFAULT_PACKAGE_JSON);
fs.writeFileSync(
path.resolve(directory, 'package.json'),
JSON.stringify(packageJson, null, 2),
Expand Down
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,7 @@
"strip-ansi": "^6.0.0",
"tempy": "^0.6.0",
"throat": "^5.0.0",
"type-fest": "^0.16.0",
"typescript": "^4.0.2",
"which": "^2.0.1"
},
Expand Down
25 changes: 14 additions & 11 deletions packages/diff-sequences/src/__tests__/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@ describe('invalid arg', () => {
});

// Return length of longest common subsequence according to Object.is method.
const countCommonObjectIs = (a: Array<any>, b: Array<any>): number => {
const countCommonObjectIs = (a: Array<unknown>, b: Array<unknown>): number => {
let n = 0;
diff(
a.length,
Expand All @@ -75,7 +75,10 @@ const countCommonObjectIs = (a: Array<any>, b: Array<any>): number => {
};

// Return length of longest common subsequence according to === operator.
const countCommonStrictEquality = (a: Array<any>, b: Array<any>): number => {
const countCommonStrictEquality = (
a: Array<unknown>,
b: Array<unknown>,
): number => {
let n = 0;
diff(
a.length,
Expand Down Expand Up @@ -133,8 +136,8 @@ const assertEnd = (name: string, val: number, end: number) => {
};

const assertCommonItems = (
a: Array<any> | string,
b: Array<any> | string,
a: Array<unknown> | string,
b: Array<unknown> | string,
nCommon: number,
aCommon: number,
bCommon: number,
Expand Down Expand Up @@ -192,9 +195,9 @@ const countDifferences = (

// Return array of items in a longest common subsequence of array-like objects.
const findCommonItems = (
a: Array<any> | string,
b: Array<any> | string,
): Array<any> => {
a: Array<unknown> | string,
b: Array<unknown> | string,
): Array<unknown> => {
const aLength = a.length;
const bLength = b.length;
const isCommon = (aIndex: number, bIndex: number) => {
Expand All @@ -205,7 +208,7 @@ const findCommonItems = (
return a[aIndex] === b[bIndex];
};

const array = [];
const array: Array<unknown> = [];
diff(
aLength,
bLength,
Expand All @@ -231,9 +234,9 @@ const findCommonItems = (

// Assert that array-like objects have the expected common items.
const expectCommonItems = (
a: Array<any> | string,
b: Array<any> | string,
expected: Array<any>,
a: Array<unknown> | string,
b: Array<unknown> | string,
expected: Array<unknown>,
) => {
expect(findCommonItems(a, b)).toEqual(expected);

Expand Down
9 changes: 4 additions & 5 deletions packages/diff-sequences/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -756,10 +756,9 @@ const findSubsequences = (
}
};

const validateLength = (name: string, arg: any) => {
const type = typeof arg;
if (type !== 'number') {
throw new TypeError(`${pkg}: ${name} typeof ${type} is not a number`);
const validateLength = (name: string, arg: unknown) => {
if (typeof arg !== 'number') {
throw new TypeError(`${pkg}: ${name} typeof ${typeof arg} is not a number`);
}
if (!Number.isSafeInteger(arg)) {
throw new RangeError(`${pkg}: ${name} value ${arg} is not a safe integer`);
Expand All @@ -769,7 +768,7 @@ const validateLength = (name: string, arg: any) => {
}
};

const validateCallback = (name: string, arg: any) => {
const validateCallback = (name: string, arg: unknown) => {
const type = typeof arg;
if (type !== 'function') {
throw new TypeError(`${pkg}: ${name} typeof ${type} is not a function`);
Expand Down
4 changes: 2 additions & 2 deletions packages/expect/src/__tests__/spyMatchers.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -179,7 +179,7 @@ const createSpy = (fn: jest.Mock) => {
].forEach(calledWith => {
const caller = function (
callee: (...a: Array<unknown>) => void,
...args: any
...args: Array<unknown>
) {
if (
calledWith === 'nthCalledWith' ||
Expand Down Expand Up @@ -739,7 +739,7 @@ const createSpy = (fn: jest.Mock) => {
].forEach(returnedWith => {
const caller = function (
callee: (...a: Array<unknown>) => void,
...args: any
...args: Array<unknown>
) {
if (
returnedWith === 'nthReturnedWith' ||
Expand Down
8 changes: 4 additions & 4 deletions packages/expect/src/asymmetricMatchers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -148,8 +148,8 @@ class ArrayContaining extends AsymmetricMatcher<Array<unknown>> {
}
}

class ObjectContaining extends AsymmetricMatcher<Record<string, any>> {
constructor(sample: Record<string, any>, inverse: boolean = false) {
class ObjectContaining extends AsymmetricMatcher<Record<string, unknown>> {
constructor(sample: Record<string, unknown>, inverse: boolean = false) {
super(sample);
this.inverse = inverse;
}
Expand Down Expand Up @@ -255,10 +255,10 @@ export const arrayContaining = (sample: Array<unknown>): ArrayContaining =>
export const arrayNotContaining = (sample: Array<unknown>): ArrayContaining =>
new ArrayContaining(sample, true);
export const objectContaining = (
sample: Record<string, any>,
sample: Record<string, unknown>,
): ObjectContaining => new ObjectContaining(sample);
export const objectNotContaining = (
sample: Record<string, any>,
sample: Record<string, unknown>,
): ObjectContaining => new ObjectContaining(sample, true);
export const stringContaining = (expected: string): StringContaining =>
new StringContaining(expected);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ export const initialize = async ({
getPrettier: () => null | any;
getBabelTraverse: () => typeof BabelTraverse;
globalConfig: Config.GlobalConfig;
localRequire: (path: Config.Path) => any;
localRequire: <T = unknown>(path: Config.Path) => T;
testPath: Config.Path;
parentProcess: Process;
sendMessageToJest?: TestFileEvent;
Expand Down
4 changes: 2 additions & 2 deletions packages/jest-circus/src/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -151,7 +151,7 @@ const _makeTimeoutMessage = (timeout: number, isHook: boolean) =>
// the original values in the variables before we require any files.
const {setTimeout, clearTimeout} = global;

function checkIsError(error: any): error is Error {
function checkIsError(error: unknown): error is Error {
return !!(error && (error as Error).message && (error as Error).stack);
}

Expand All @@ -160,7 +160,7 @@ export const callAsyncCircusFn = (
testContext: Circus.TestContext | undefined,
asyncError: Circus.Exception,
{isHook, timeout}: {isHook?: boolean | null; timeout: number},
): Promise<any> => {
): Promise<unknown> => {
let timeoutID: NodeJS.Timeout;
let completed = false;

Expand Down
2 changes: 1 addition & 1 deletion packages/jest-cli/src/init/generate_config_file.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ const generateConfigFile = (
): string => {
const {coverage, coverageProvider, clearMocks, environment} = results;

const overrides: Record<string, any> = {};
const overrides: Record<string, unknown> = {};

if (coverage) {
Object.assign(overrides, {
Expand Down
4 changes: 2 additions & 2 deletions packages/jest-config/src/normalize.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1007,9 +1007,9 @@ export default function normalize(
newOptions.watchAll = false;
}

// as any since it can happen. We really need to fix the types here
// as unknown since it can happen. We really need to fix the types here
if (
newOptions.moduleNameMapper === (DEFAULT_CONFIG.moduleNameMapper as any)
newOptions.moduleNameMapper === (DEFAULT_CONFIG.moduleNameMapper as unknown)
) {
newOptions.moduleNameMapper = [];
}
Expand Down
10 changes: 5 additions & 5 deletions packages/jest-core/src/__tests__/watch-file-changes.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ import type {AggregatedResult} from '@jest/test-result';
describe('Watch mode flows with changed files', () => {
jest.resetModules();

let watch: any;
let watch: unknown;
let pipe: NodeJS.ReadStream;
let stdin: MockStdin;
const testDirectory = path.resolve(tmpdir(), 'jest-tmp');
Expand All @@ -33,7 +33,7 @@ describe('Watch mode flows with changed files', () => {

beforeEach(() => {
watch = require('../watch').default;
pipe = {write: jest.fn()} as any;
pipe = {write: jest.fn()} as unknown;
stdin = new MockStdin();
rimraf.sync(cacheDirectory);
rimraf.sync(testDirectory);
Expand Down Expand Up @@ -79,7 +79,7 @@ describe('Watch mode flows with changed files', () => {
watch: false,
watchman: false,
},
{} as any,
{} as unknown,
).options;

hasteMapInstance = await Runtime.createHasteMap(config, {
Expand Down Expand Up @@ -165,7 +165,7 @@ describe('Watch mode flows with changed files', () => {
});

class MockStdin {
private _callbacks: Array<any>;
private _callbacks: Array<unknown>;

constructor() {
this._callbacks = [];
Expand All @@ -175,7 +175,7 @@ class MockStdin {

setEncoding() {}

on(_: any, callback: any) {
on(_: unknown, callback: unknown) {
this._callbacks.push(callback);
}

Expand Down
2 changes: 1 addition & 1 deletion packages/jest-each/src/validation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ export const validateArrayTable = (table: unknown): void => {
};

const isTaggedTemplateLiteral = (array: any) => array.raw !== undefined;
const isEmptyTable = (table: Array<any>) => table.length === 0;
const isEmptyTable = (table: Array<unknown>) => table.length === 0;
const isEmptyString = (str: string | unknown) =>
typeof str === 'string' && str.trim() === '';

Expand Down
2 changes: 1 addition & 1 deletion packages/jest-haste-map/src/ModuleMap.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ export default class ModuleMap {
private json: SerializableModuleMap | undefined;

private static mapToArrayRecursive(
map: Map<any, any>,
map: Map<string, any>,
): Array<[string, unknown]> {
let arr = Array.from(map);
if (arr[0] && arr[0][1] instanceof Map) {
Expand Down
4 changes: 2 additions & 2 deletions packages/jest-haste-map/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -381,7 +381,7 @@ class HasteMap extends EventEmitter {
let hasteMap: InternalHasteMap;

try {
hasteMap = serializer.readFileSync(this._cachePath);
hasteMap = serializer.readFileSync(this._cachePath) as any;
} catch {
hasteMap = this._createEmptyMap();
}
Expand Down Expand Up @@ -1111,7 +1111,7 @@ class DuplicateError extends Error {
}
}

function copy<T extends Record<string, any>>(object: T): T {
function copy<T extends Record<string, unknown>>(object: T): T {
return Object.assign(Object.create(null), object);
}

Expand Down
4 changes: 2 additions & 2 deletions packages/jest-jasmine2/src/PCancelable.ts
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ export default class PCancelable<T> extends Promise<T> {
| undefined
| null,
onRejected?:
| ((reason: any) => TResult2 | PromiseLike<TResult2>)
| ((reason: unknown) => TResult2 | PromiseLike<TResult2>)
| undefined
| null,
): Promise<TResult1 | TResult2> {
Expand All @@ -62,7 +62,7 @@ export default class PCancelable<T> extends Promise<T> {

catch<TResult>(
onRejected?:
| ((reason: any) => TResult | PromiseLike<TResult>)
| ((reason: unknown) => TResult | PromiseLike<TResult>)
| undefined
| null,
): Promise<T | TResult> {
Expand Down
2 changes: 1 addition & 1 deletion packages/jest-jasmine2/src/jasmine/ReportDispatcher.ts
Original file line number Diff line number Diff line change
Expand Up @@ -79,7 +79,7 @@ export default class ReportDispatcher implements Reporter {

return this;

function dispatch(method: keyof Reporter, args: any) {
function dispatch(method: keyof Reporter, args: unknown) {
if (reporters.length === 0 && fallbackReporter !== null) {
reporters.push(fallbackReporter);
}
Expand Down
4 changes: 2 additions & 2 deletions packages/jest-jasmine2/src/jasmine/createSpy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,8 +34,8 @@ import type {Spy} from '../types';
import CallTracker, {Context} from './CallTracker';
import SpyStrategy from './SpyStrategy';

interface Fn extends Record<string, any> {
(): any;
interface Fn extends Record<string, unknown> {
(): unknown;
}

function createSpy(name: string, originalFn: Fn): Spy {
Expand Down
2 changes: 1 addition & 1 deletion packages/jest-jasmine2/src/queueRunner.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ export type Options = {
onException: (error: Error) => void;
queueableFns: Array<QueueableFn>;
setTimeout: Global['setTimeout'];
userContext: any;
userContext: unknown;
};

export interface DoneFn {
Expand Down
10 changes: 5 additions & 5 deletions packages/jest-jasmine2/src/treeProcessor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,13 +15,13 @@ type Options = {
};

export type TreeNode = {
afterAllFns: Array<any>;
beforeAllFns: Array<any>;
afterAllFns: Array<unknown>;
beforeAllFns: Array<unknown>;
disabled?: boolean;
execute: (onComplete: () => void, enabled: boolean) => void;
id: string;
onException: (error: Error) => void;
sharedUserContext: () => any;
sharedUserContext: () => unknown;
children?: Array<TreeNode>;
} & Pick<Suite, 'getResult' | 'parentSuite' | 'result' | 'markedPending'>;

Expand All @@ -46,13 +46,13 @@ export default function treeProcessor(options: Options): void {
}

function getNodeWithoutChildrenHandler(node: TreeNode, enabled: boolean) {
return function fn(done: (error?: any) => void = () => {}) {
return function fn(done: (error?: unknown) => void = () => {}) {
node.execute(done, enabled);
};
}

function getNodeWithChildrenHandler(node: TreeNode, enabled: boolean) {
return async function fn(done: (error?: any) => void = () => {}) {
return async function fn(done: (error?: unknown) => void = () => {}) {
nodeStart(node);
await queueRunnerFactory({
onException: (error: Error) => node.onException(error),
Expand Down
Loading

0 comments on commit 7e71d5f

Please sign in to comment.