Skip to content

Latest commit

 

History

History
100 lines (71 loc) · 3.54 KB

File metadata and controls

100 lines (71 loc) · 3.54 KB

Item 5: Limit Use of the any Type

Things to Remember

  • TypeScript's any type allows you to disable most forms of type checking for a symbol.
  • The any type eliminates type safety, lets you break contracts, harms developer experience, makes refactoring error prone, hides your type design, and undermines confidence in the type system.
  • Avoid using any when you can!

Code Samples

let ageInYears: number;
ageInYears = '12';
// ~~~~~~~ Type 'string' is not assignable to type 'number'.
ageInYears = '12' as any;  // OK

💻 playground


ageInYears += 1;  // OK; at runtime, ageInYears is now "121"

💻 playground


function calculateAge(birthDate: Date): number {
  // ...
}

let birthDate: any = '1990-01-19';
calculateAge(birthDate);  // OK

💻 playground


interface Person {
  first: string;
  last: string;
}

const formatName = (p: Person) => `${p.first} ${p.last}`;
const formatNameAny = (p: any) => `${p.first} ${p.last}`;

💻 playground


interface Person {
  firstName: string;
  last: string;
}
const formatName = (p: Person) => `${p.firstName} ${p.last}`;
const formatNameAny = (p: any) => `${p.first} ${p.last}`;

💻 playground


interface ComponentProps {
  onSelectItem: (item: any) => void;
}

💻 playground


function renderSelector(props: ComponentProps) { /* ... */ }

let selectedId: number = 0;
function handleSelectItem(item: any) {
  selectedId = item.id;
}

renderSelector({onSelectItem: handleSelectItem});

💻 playground


interface ComponentProps {
  onSelectItem: (id: number) => void;
}

💻 playground