TypeScript is a language built on top of JavaScript that adds "data types" to it. Any code you write in JavaScript is also valid in TypeScript, but you can specify the type of each variable or function input. Browsers do not run TypeScript directly; the code is translated into ordinary JavaScript before it runs.
A simple example#
function total(price: number, count: number) {
return price * count;
}
total("100", 2); // error while writing the codeIn plain JavaScript, passing text instead of a number shows no problem until run time, and you might get a strange result. In TypeScript the editor warns you right away.
Why it is used#
- Finding type errors before the code reaches the user
- More precise auto-completion and better guidance in the editor
- Code that is easier for large teams to read, because the inputs and outputs of each function are clear
- Safer rewriting of large projects
Where you run into it#
Many modern web frameworks and libraries are written in TypeScript or support it. If you see files with a .ts or .tsx extension in a project, you are dealing with this language.
A common mistake#
TypeScript does not replace testing; it only reveals one class of errors earlier. For a small, throwaway project, the effort of setting it up may not be worth it.