Skip to content

Latest commit

 

History

History
124 lines (97 loc) · 5.12 KB

narrowest-any.md

File metadata and controls

124 lines (97 loc) · 5.12 KB

Item 43: Use the Narrowest Possible Scope for any Types

Things to Remember

  • Make your uses of any as narrowly scoped as possible to avoid undesired loss of type safety elsewhere in your code.
  • Never return an any type from a function. This will silently lead to the loss of type safety for code that calls the function.
  • Use as any on individual properties of a larger object instead of the whole object.

Code Samples

declare function getPizza(): Pizza;
function eatSalad(salad: Salad) { /* ... */ }

function eatDinner() {
  const pizza = getPizza();
  eatSalad(pizza);
  //       ~~~~~
  // Argument of type 'Pizza' is not assignable to parameter of type 'Salad'
  pizza.slice();
}

💻 playground


function eatDinner1() {
  const pizza: any = getPizza();  // Don't do this
  eatSalad(pizza);  // ok
  pizza.slice();  // This call is unchecked!
}

function eatDinner2() {
  const pizza = getPizza();
  eatSalad(pizza as any);  // This is preferable
  pizza.slice();  // this is safe
}

💻 playground


function eatDinner1() {
  const pizza: any = getPizza();
  eatSalad(pizza);
  pizza.slice();
  return pizza;  // unsafe pizza!
}

function spiceItUp() {
  const pizza = eatDinner1();
  //    ^? const pizza: any
  pizza.addRedPepperFlakes();  // This call is also unchecked!
}

💻 playground


function eatDinner1() {
  const pizza = getPizza();
  // @ts-ignore
  eatSalad(pizza);
  pizza.slice();
}

function eatDinner2() {
  const pizza = getPizza();
  // @ts-expect-error
  eatSalad(pizza);
  pizza.slice();
}

💻 playground


const config: Config = {
  a: 1,
  b: 2,
  c: {
    key: value
 // ~~~ Property ... missing in type 'Bar' but required in type 'Foo'
  }
};

💻 playground


const config: Config = {
  a: 1,
  b: 2,
  c: {
    key: value
  }
} as any;  // Don't do this!

💻 playground


const config: Config = {
  a: 1,
  b: 2,  // These properties are still checked
  c: {
    key: value as any
  }
};

💻 playground