Item 44: Prefer More Precise Variants of any to Plain any
要点
- 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. - 当你使用
any
时,考虑是否真的允许任何 JavaScript 值。 - 如果更准确地描述数据,优先使用更精确的
any
形式,如any[]
、{[id: string]: any}
或() => any
。
正文
ts
function getLengthBad(array: any) {
// Don't do this!
return array.length
}
function getLength(array: any[]) {
// This is better
return array.length
}
ts
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[]'.
ts
function hasAKeyThatEndsWithZ(o: Record<string, any>) {
for (const key in o) {
if (key.endsWith('z')) {
console.log(key, o[key])
return true
}
}
return false
}
ts
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
}
ts
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
ts
const numArgsBad = (...args: any) => args.length
// ^? const numArgsBad: (...args: any) => any
const numArgsBetter = (...args: any[]) => args.length
// ^? const numArgsBetter: (...args: any[]) => number