When we create applications in Angular, the any type is our "live-saver" when struggle with complex error messages, want to save time by not writing specific type definitions, or think that TypeScript's type checking limits our coding flexibility and freedom.
Using the any type might seem like an easy solution to common problems, but it's important for developers to think about the hidden issues and the real effects of using this simple method.
Using the any type a lot can accidentally weaken TypeScript main purpose, which is to make code safer and find errors early. Ignoring the advantages of checking types can lead to hidden mistakes, harder-to-maintain code, and more complex code.
Today, I will to show few reasons with examples, why I avoid using any and instead embrace unknown. I will also discuss how to utilize TypeScript utility types to create flexible new types. Let's get started.
Type Safety
When you pick any type might seem like an easy solution for typing issues. However, this choice has a big drawback: we lose type safety, which is the main feature of TypeScript, to ensuring your code works correctly.
I want to show the dangers of not considering type safety with any, and highlight how important TypeScript's type system is.
Consider the following code snippet, we have the accountBalance method which expects an account and amount to update the balance.
export class Accounting {
  accountBalance(account: any, amount:any) {
    return account.balance += amount;
  }
}
Since the accountBalance method expects an 'any' type for both account and amount, I can pass the following parameters:
let accounting = new Accounting()
let balanceA = accounting.accountBalance({accountNumber: '05654613', balance: 15}, 26)    
let balanceB = accounting.accountBalance({accountNumber: '05654613', balance: 15}, '26')
console.log({balanceA, balanceB})
Is this the expected result? Why does everything compile and appear to work fine, but fail during runtime?
When working with TypeScript, we expect TypeScript, the IDE, or the compiler to warn us about these kinds of issues 🤦♂️.
Why doesn't the compiler warn about the issue? I believe the most effective solution is to introduce the Account type.
export type Account = {
  accountNumber: string;
  balance: number;
}
Change the signature of the accountBalance function to use the Account type
 accountBalance(account: Account, amount: number): number {
    return (account.total += amount);
  }
With appropriate typing, the IDE, compiler, and application all notify us of potential issues.








    
Top comments (1)
Take your TypeScript skills to new heights with "Mastering TypeScript Core Utility Types":
📖 Buy on Leanpub
📖 Buy on Amazon
Some comments have been hidden by the post's author - find out more