Skip to content

Item 43: Use the Narrowest Possible Scope for any Types

要点

  • 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.
  • 尽可能将 any 的使用范围限定得尽量窄,以避免在代码的其他地方丧失类型安全。
  • 永远不要从函数中返回 any 类型。这会悄悄导致调用该函数的代码失去类型安全。
  • 对于较大的对象,最好只对单个属性使用 as any,而不是对整个对象使用。

正文

ts
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


ts
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


ts
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


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

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

💻 playground


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

💻 playground


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

💻 playground


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

💻 playground

Released under the MIT License.