Why use TypeScript?
Have you ever looked at a codebase you are not familiar with and when looking at existing functions you couldn’t tell what type of arguments does it expect or what does it return? TypeScript solves this problem by adding types to JavaScript. Here’s an example of a function in JavaScript:- What structure
itemsshould have. We can guess it’s an array of objects with price and quantity properties, but it’s not specified. - What type
taxRateshould be. It seems like it should be a number, but there’s nothing preventing a caller from passing something else, like a string. - What the function returns. It seems to return a number (the total cost), but there’s no explicit guarantee.
- The items parameter is explicitly an array of Item objects, where Item is a type with price and quantity as numbers. This prevents passing in an array of objects that don’t match the expected structure.
- The taxRate parameter is explicitly a number, preventing callers from passing a value of another type.
- The function is explicitly defined to return a number, clarifying the expected output and ensuring the function implementation adheres to this contract.
label property to the object that is being passed to the function. You should see TypeScript complaining about the type mismatch as the type Item is not expecting a label property.
Common mistakes and Standards
- Don’t use
anytype unless you really have to. It defeats the purpose of using TypeScript. - Avoid using
Interfacewhen you can useType.Typeis more flexible and can be used to define union types, intersection types, and more. - Basic types like
string,number,boolean,object,arrayare lowercase.String,Number,Boolean,Object,Arrayare classes and should be avoided.