Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

chore: replace anys with unknowns #9626

Merged
merged 9 commits into from
Apr 5, 2020
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@

### Chore & Maintenance

- `[*]` Replace `any`s with `unknown`s ([#9626](https://github.com/facebook/jest/pull/9626))
- `[@jest/transform]` Expose type `CacheKeyOptions` for `getCacheKey` ([#9762](https://github.com/facebook/jest/pull/9762))

### Performance
Expand Down
4 changes: 2 additions & 2 deletions packages/expect/src/matchers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@ const toStrictEqualTesters = [
type ContainIterable =
| Array<unknown>
| Set<unknown>
| NodeListOf<any>
| NodeListOf<Node>
| DOMTokenList
| HTMLCollectionOf<any>;

Expand Down Expand Up @@ -630,7 +630,7 @@ const matchers: MatchersObject = {

if (
typeof received !== 'string' &&
(!received || typeof received.length !== 'number')
(typeof received !== 'object' || typeof received.length !== 'number')
) {
throw new Error(
matcherErrorMessage(
Expand Down
2 changes: 1 addition & 1 deletion packages/expect/src/toThrowMatchers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -223,7 +223,7 @@ const toThrowExpectedObject = (
matcherName: string,
options: MatcherHintOptions,
thrown: Thrown | null,
expected: any,
expected: Error,
): SyncExpectationResult => {
const pass = thrown !== null && thrown.message === expected.message;

Expand Down
15 changes: 9 additions & 6 deletions packages/jest-cli/src/cli/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -74,12 +74,15 @@ export const buildArgv = (maybeArgv?: Array<string>): Config.Argv => {
);

// strip dashed args
return Object.keys(argv).reduce((result, key) => {
if (!key.includes('-')) {
result[key] = argv[key];
}
return result;
}, {} as Config.Argv);
return Object.keys(argv).reduce<Config.Argv>(
(result, key) => {
if (!key.includes('-')) {
result[key] = argv[key];
}
return result;
},
{$0: argv.$0, _: argv._},
);
};

const getProjectListFromCLIArgs = (
Expand Down
2 changes: 1 addition & 1 deletion packages/jest-config/src/ReporterValidationErrors.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ export function createArrayReporterError(
arrayReporter: Config.ReporterConfig,
reporterIndex: number,
valueIndex: number,
value: string | Record<string, any>,
value: string | Record<string, unknown>,
expectedType: string,
valueName: string,
): ValidationError {
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 @@ -746,14 +746,14 @@ export default function normalize(
? _replaceRootDirTags(options.rootDir, project)
: project,
)
.reduce((projects, project) => {
.reduce<Array<string>>((projects, project) => {
// Project can be specified as globs. If a glob matches any files,
// We expand it to these paths. If not, we keep the original path
// for the future resolution.
const globMatches =
typeof project === 'string' ? glob(project) : [];
return projects.concat(globMatches.length ? globMatches : project);
}, [] as Array<string>);
}, []);
break;
case 'moduleDirectories':
case 'testMatch':
Expand Down
4 changes: 2 additions & 2 deletions packages/jest-core/src/FailedTestsCache.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,10 +29,10 @@ export default class FailedTestsCache {
.reduce<TestMap>((suiteMap, testResult) => {
suiteMap[testResult.testFilePath] = testResult.testResults
.filter(test => test.status === 'failed')
.reduce((testMap, test) => {
.reduce<{[name: string]: true}>((testMap, test) => {
testMap[test.fullName] = true;
return testMap;
}, {} as {[name: string]: true});
}, {});
return suiteMap;
}, {});

Expand Down
8 changes: 5 additions & 3 deletions packages/jest-core/src/watch.ts
Original file line number Diff line number Diff line change
Expand Up @@ -158,9 +158,11 @@ export default function watch(
if (globalConfig.watchPlugins != null) {
const watchPluginKeys: WatchPluginKeysMap = new Map();
for (const plugin of watchPlugins) {
const reservedInfo =
RESERVED_KEY_PLUGINS.get(plugin.constructor as WatchPluginClass) ||
({} as ReservedInfo);
const reservedInfo: Pick<
ReservedInfo,
'forbiddenOverwriteMessage' | 'key'
> =
RESERVED_KEY_PLUGINS.get(plugin.constructor as WatchPluginClass) || {};
const key = reservedInfo.key || getPluginKey(plugin, globalConfig);
if (!key) {
continue;
Expand Down
12 changes: 5 additions & 7 deletions packages/jest-docblock/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ const ltrimNewlineRe = /^(\r?\n)+/;
const multilineRe = /(?:^|\r?\n) *(@[^\r\n]*?) *\r?\n *(?![^@\r\n]*\/\/[^]*)([^@\r\n\s][^@\r\n]+?) *\r?\n/g;
const propertyRe = /(?:^|\r?\n) *@(\S+) *([^\r\n]*)/g;
const stringStartRe = /(\r?\n|^) *\* ?/g;
const STRING_ARRAY: ReadonlyArray<string> = [];

export function extract(contents: string): string {
const match = contents.match(docblockRe);
Expand Down Expand Up @@ -65,10 +66,7 @@ export function parseWithComments(
typeof result[match[1]] === 'string' ||
Array.isArray(result[match[1]])
) {
result[match[1]] = ([] as Array<string>).concat(
result[match[1]],
nextPragma,
);
result[match[1]] = STRING_ARRAY.concat(result[match[1]], nextPragma);
} else {
result[match[1]] = nextPragma;
}
Expand Down Expand Up @@ -123,7 +121,7 @@ export function print({
}

function printKeyValues(key: string, valueOrArray: string | Array<string>) {
return ([] as Array<string>)
.concat(valueOrArray)
.map(value => `@${key} ${value}`.trim());
return STRING_ARRAY.concat(valueOrArray).map(value =>
`@${key} ${value}`.trim(),
);
}
2 changes: 1 addition & 1 deletion packages/jest-fake-timers/src/jestFakeTimers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -372,7 +372,7 @@ export default class FakeTimers<TimerRef> {
const promisifiableFakeSetTimeout = fn(this._fakeSetTimeout.bind(this));
promisifiableFakeSetTimeout[util.promisify.custom] = (
delay?: number,
arg?: any,
arg?: unknown,
) =>
new Promise(resolve => promisifiableFakeSetTimeout(resolve, delay, arg));

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 @@ -18,7 +18,7 @@ import type {
import * as fastPath from './lib/fast_path';
import H from './constants';

const EMPTY_OBJ = {} as Record<string, any>;
const EMPTY_OBJ: Record<string, ModuleMetaData> = {};
const EMPTY_MAP = new Map();

type ValueType<T> = T extends Map<string, infer V> ? V : never;
Expand Down
2 changes: 1 addition & 1 deletion packages/jest-jasmine2/src/jasmine/Env.ts
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,7 @@ export default function (j$: Jasmine) {
) => Promise<void>;
fdescribe: (description: string, specDefinitions: Function) => Suite;
spyOn: (
obj: Record<string, any>,
obj: Record<string, Spy>,
methodName: string,
accessType?: keyof PropertyDescriptor,
) => Spy;
Expand Down
9 changes: 6 additions & 3 deletions packages/jest-jasmine2/src/jasmine/spyRegistry.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,10 @@ const formatErrorMsg = (domain: string, usage?: string) => {
return (msg: string) => domain + ' : ' + msg + usageDefinition;
};

function isSpy(putativeSpy: any) {
function isSpy(putativeSpy: {
and: unknown;
calls: unknown;
}): putativeSpy is Spy {
if (!putativeSpy) {
return false;
}
Expand All @@ -54,15 +57,15 @@ const getErrorMsg = formatErrorMsg('<spyOn>', 'spyOn(<object>, <methodName>)');
export default class SpyRegistry {
allowRespy: (allow: unknown) => void;
spyOn: (
obj: Record<string, any>,
obj: Record<string, Spy>,
methodName: string,
accessType?: keyof PropertyDescriptor,
) => Spy;
clearSpies: () => void;
respy: unknown;

private _spyOnProperty: (
obj: Record<string, any>,
obj: Record<string, Spy>,
propertyName: string,
accessType: keyof PropertyDescriptor,
) => Spy;
Expand Down
15 changes: 9 additions & 6 deletions packages/jest-message-util/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -321,12 +321,15 @@ export const formatResultsErrors = (
options: StackTraceOptions,
testPath?: Path,
): string | null => {
const failedResults: FailedResults = testResults.reduce((errors, result) => {
result.failureMessages
.map(checkForCommonEnvironmentErrors)
.forEach(content => errors.push({content, result}));
return errors;
}, [] as FailedResults);
const failedResults: FailedResults = testResults.reduce<FailedResults>(
(errors, result) => {
result.failureMessages
.map(checkForCommonEnvironmentErrors)
.forEach(content => errors.push({content, result}));
return errors;
},
[],
);

if (!failedResults.length) {
return null;
Expand Down
4 changes: 2 additions & 2 deletions packages/jest-resolve/src/nodeModulesPaths.ts
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ export default function nodeModulesPaths(
}

const dirs = paths
.reduce(
.reduce<Array<Config.Path>>(
(dirs, aPath) =>
dirs.concat(
modules.map(moduleDir =>
Expand All @@ -65,7 +65,7 @@ export default function nodeModulesPaths(
: path.join(prefix, aPath, moduleDir),
),
),
[] as Array<Config.Path>,
[],
)
.filter(dir => dir !== '');

Expand Down
23 changes: 11 additions & 12 deletions packages/jest-validate/src/validateCLIOptions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -87,19 +87,18 @@ export default function validateCLIOptions(
throw createCLIValidationError(unrecognizedOptions, allowedOptions);
}

const CLIDeprecations = Object.keys(deprecationEntries).reduce(
(acc, entry) => {
if (options[entry]) {
acc[entry] = deprecationEntries[entry];
const alias = options[entry].alias as string;
if (alias) {
acc[alias] = deprecationEntries[entry];
}
const CLIDeprecations = Object.keys(deprecationEntries).reduce<
Record<string, Function>
>((acc, entry) => {
if (options[entry]) {
acc[entry] = deprecationEntries[entry];
const alias = options[entry].alias as string;
if (alias) {
acc[alias] = deprecationEntries[entry];
}
return acc;
},
{} as Record<string, Function>,
);
}
return acc;
}, {});
const deprecations = new Set(Object.keys(CLIDeprecations));
const deprecatedOptions = Object.keys(argv).filter(
arg => deprecations.has(arg) && argv[arg] != null,
Expand Down
6 changes: 3 additions & 3 deletions packages/pretty-format/src/collections.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ const getKeysOfEnumerableProperties = (object: Record<string, any>) => {
* without surrounding punctuation (for example, braces)
*/
export function printIteratorEntries(
iterator: Iterator<any>,
iterator: Iterator<[unknown, unknown]>,
config: Config,
indentation: string,
depth: number,
Expand Down Expand Up @@ -86,7 +86,7 @@ export function printIteratorEntries(
* without surrounding punctuation (braces or brackets)
*/
export function printIteratorValues(
iterator: Iterator<any>,
iterator: Iterator<unknown>,
config: Config,
indentation: string,
depth: number,
Expand Down Expand Up @@ -165,7 +165,7 @@ export function printListItems(
* without surrounding punctuation (for example, braces)
*/
export function printObjectProperties(
val: Record<string, any>,
val: Record<string, unknown>,
config: Config,
indentation: string,
depth: number,
Expand Down
2 changes: 1 addition & 1 deletion packages/pretty-format/src/plugins/ConvertAnsi.ts
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ const toHumanReadableAnsi = (text: string) =>
}
});

export const test: NewPlugin['test'] = (val: any) =>
export const test: NewPlugin['test'] = (val: unknown) =>
typeof val === 'string' && !!val.match(ansiRegex());

export const serialize: NewPlugin['serialize'] = (
Expand Down
23 changes: 13 additions & 10 deletions packages/pretty-format/src/plugins/DOMCollection.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,20 +17,17 @@ const ARRAY_REGEXP = /^(HTML\w*Collection|NodeList)$/;
const testName = (name: any) =>
OBJECT_NAMES.indexOf(name) !== -1 || ARRAY_REGEXP.test(name);

export const test: NewPlugin['test'] = (val: any) =>
export const test: NewPlugin['test'] = (val: object) =>
val &&
val.constructor &&
val.constructor.name &&
!!val.constructor.name &&
testName(val.constructor.name);

// Convert array of attribute objects to props object.
const propsReducer = (props: any, attribute: any) => {
props[attribute.name] = attribute.value;
return props;
};
const isNamedNodeMap = (collection: object): collection is NamedNodeMap =>
collection.constructor.name === 'NamedNodeMap';

export const serialize: NewPlugin['serialize'] = (
collection: any,
collection: any | NamedNodeMap,
config: Config,
indentation: string,
depth: number,
Expand All @@ -47,8 +44,14 @@ export const serialize: NewPlugin['serialize'] = (
(OBJECT_NAMES.indexOf(name) !== -1
? '{' +
printObjectProperties(
name === 'NamedNodeMap'
? Array.prototype.reduce.call(collection, propsReducer, {})
isNamedNodeMap(collection)
? Array.from(collection).reduce<Record<string, string>>(
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I inlined this function as there's no way to pass a generic parameter otherwise; it's inlined in DOMElement, and so now actually matches 1:1.

(props, attribute) => {
props[attribute.name] = attribute.value;
return props;
},
{},
)
: {...collection},
config,
indentation,
Expand Down
15 changes: 9 additions & 6 deletions packages/pretty-format/src/plugins/DOMElement.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ const FRAGMENT_NODE = 11;

const ELEMENT_REGEXP = /^((HTML|SVG)\w*)?Element$/;

const testNode = (nodeType: any, name: any) =>
const testNode = (nodeType: number, name: string) =>
(nodeType === ELEMENT_NODE && ELEMENT_REGEXP.test(name)) ||
(nodeType === TEXT_NODE && name === 'Text') ||
(nodeType === COMMENT_NODE && name === 'Comment') ||
Expand Down Expand Up @@ -82,11 +82,14 @@ export const serialize: NewPlugin['serialize'] = (
.map(attr => attr.name)
.sort(),
nodeIsFragment(node)
? []
: Array.from(node.attributes).reduce((props, attribute) => {
props[attribute.name] = attribute.value;
return props;
}, {} as any),
? {}
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This could actually be classed as a bug - it might not ever be reachable due to surrounding code, but still - it was an array when it should have been an object 🤷‍♂

: Array.from(node.attributes).reduce<Record<string, string>>(
(props, attribute) => {
props[attribute.name] = attribute.value;
return props;
},
{},
),
config,
indentation + config.indent,
depth,
Expand Down
4 changes: 2 additions & 2 deletions packages/pretty-format/src/plugins/ReactElement.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ import {

// Given element.props.children, or subtree during recursive traversal,
// return flattened array of children.
const getChildren = (arg: Array<any>, children = []) => {
const getChildren = (arg: Array<unknown>, children = []) => {
if (Array.isArray(arg)) {
arg.forEach(item => {
getChildren(item, children);
Expand Down Expand Up @@ -115,7 +115,7 @@ export const serialize: NewPlugin['serialize'] = (
indentation,
);

export const test: NewPlugin['test'] = (val: any) =>
export const test: NewPlugin['test'] = (val: unknown) =>
val && ReactIs.isElement(val);

const plugin: NewPlugin = {serialize, test};
Expand Down
Loading