TypeScript
- 2021年5月21日
- 技術情報
TypeScript stands in an unusual relationship to JavaScript. TypeScript offers all of JavaScript’s features, and an additional layer on top of these: TypeScript’s type system.
TypeScript is a modern age JavaScript development language.
There are a lot of benefits of adding static typing to JavaScript. You’ll not see that undefined pop up in your applications anymore. Refactoring code will not be a nightmare anymore. And many more. A study shows that 15% of JavaScript bugs can be detected by TypeScript.
Types — The difference between JS and TS
Programming languages fall into two categories: statically typed or dynamically typed.
Function getWidth(width){
return num + 3
}
Here, the type of variable width is not known. If I call this with, getWidth(“I love TS”) it will print I love TS3. This is known as type coercion. If it can, Javascript will see that it is trying to add a string and a number together, and it will convert the number to its string equivalent and concatenate them.
With TypeScript, I could do the following:
function getWidth(width: number) {
return num + 3
}
We just added the type of variable width as a number
. If I call add(“I love TS”)
now, it’ll throw a compilation error — Argument of type string
is not assignable to parameter of type number
.
Catching the error instantly allows me to save time and check why my input is not the type I think it is, rather than having to trace my steps back much later in the process without being sure where the error is occurring.
Benefits of Static Typing
- TypeScript is that it offers the ability to add static types to your JavaScript code.
- Static typing allows you to catch errors earlier in the debugging process.
- Adding strict types makes code more readable. A code that speaks for itself can offset the lack of direct communication between team members.
By Ami
asahi at 2021年05月21日 10:00:50