- When you use
any
, think about whether any JavaScript value is truly permissible. - Prefer more precise forms of
any
such asany[]
or{[id: string]: any}
or() => any
if they more accurately model your data.
// TODO: I don't love these examples since they could all be replaced with unknown[]
.
function getLengthBad(array: any) { // Don't do this!
return array.length;
}
function getLength(array: any[]) { // This is better
return array.length;
}
getLengthBad(/123/); // No error, returns undefined
getLength(/123/);
// ~~~~~
// Argument of type 'RegExp' is not assignable to parameter of type 'any[]'.
getLengthBad(null); // No error, throws at runtime
getLength(null);
// ~~~~
// Argument of type 'null' is not assignable to parameter of type 'any[]'.
function hasAKeyThatEndsWithZ(o: Record<string, any>) {
for (const key in o) {
if (key.endsWith('z')) {
console.log(key, o[key]);
return true;
}
}
return false;
}
function hasAKeyThatEndsWithZ(o: object) {
for (const key in o) {
if (key.endsWith('z')) {
console.log(key, o[key]);
// ~~~~~~ Element implicitly has an 'any' type
// because type '{}' has no index signature
return true;
}
}
return false;
}
type Fn0 = () => any; // any function callable with no params
type Fn1 = (arg: any) => any; // With one param
type FnN = (...args: any[]) => any; // With any number of params
// same as "Function" type
const numArgsBad = (...args: any) => args.length;
// ^? const numArgsBad: (...args: any) => any
const numArgsBetter = (...args: any[]) => args.length;
// ^? const numArgsBetter: (...args: any[]) => number