Skip to content

Latest commit

 

History

History
94 lines (71 loc) · 4.37 KB

specific-any.md

File metadata and controls

94 lines (71 loc) · 4.37 KB

Item 44: Prefer More Precise Variants of any to Plain any

Things to Remember

  • When you use any, think about whether any JavaScript value is truly permissible.
  • Prefer more precise forms of any such as any[] 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[].

Code Samples

function getLengthBad(array: any) {  // Don't do this!
  return array.length;
}

function getLength(array: any[]) {  // This is better
  return array.length;
}

💻 playground


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[]'.

💻 playground


function hasAKeyThatEndsWithZ(o: Record<string, any>) {
  for (const key in o) {
    if (key.endsWith('z')) {
      console.log(key, o[key]);
      return true;
    }
  }
  return false;
}

💻 playground


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;
}

💻 playground


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

💻 playground


const numArgsBad = (...args: any) => args.length;
//    ^? const numArgsBad: (...args: any) => any
const numArgsBetter = (...args: any[]) => args.length;
//    ^? const numArgsBetter: (...args: any[]) => number

💻 playground