The Intellisense
Javascript is a weakly typed programming language. This means that there's no way to know the exact type of a variable before your code runs. Let's take a look at the following example:
1function formatName(user) { 2 return `${user.name}, ${user.age}`; 3}
Here we relying on the fact that the "user" parameter is an object that contains the "name" and "age" properties. We're trusting the user of this function to pass the correctly typed parameter.
In the real world, the data passed to this function can come from various sources:
The shocking truth is that you can also be the source of an error 😱. So...
1type User = { 2 name: string; 3 age: number; 4} 5 6function formatName(user: User) { 7 return `${user.name}, ${user.age}`; 8}
In the Typescript example, we set the conditions that need to be met by the "user" parameter. We're ensuring that it's safe to assume the user has a "name" and "age", and we also get the sweet-sweet intellisense!
💡 Some might say that we can still pass any paramter to this function, as long as we cast the type to "any". This is true, but at that point, the developer has already been warned and is now taking the responsibility of explicitly casting the parameter type.
At that point, it's the developer's fault. 🤷