You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
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
declarefunctiongetPizza(): Pizza;functioneatSalad(salad: Salad){/* ... */}functioneatDinner(){constpizza=getPizza();eatSalad(pizza);// ~~~~~// Argument of type 'Pizza' is not assignable to parameter of type 'Salad'pizza.slice();}
functioneatDinner1(){constpizza: any=getPizza();// Don't do thiseatSalad(pizza);// okpizza.slice();// This call is unchecked!}functioneatDinner2(){constpizza=getPizza();eatSalad(pizzaasany);// This is preferablepizza.slice();// this is safe}
functioneatDinner1(){constpizza: any=getPizza();eatSalad(pizza);pizza.slice();returnpizza;// unsafe pizza!}functionspiceItUp(){constpizza=eatDinner1();// ^? const pizza: anypizza.addRedPepperFlakes();// This call is also unchecked!}