
What is TypeScript?
What is TypeScript? 관련
Before diving into what TypeScript is, it's important to understand why it was created. JavaScript is a loosely typed language, meaning variables are defined and their types are determined at runtime. This flexibility can lead to unexpected behavior, especially in larger projects.
For example, you might accidentally assign a value of the wrong type to a variable, resulting in errors that you only discover when the code is executed.
Here’s an example of JavaScript that demonstrates this issue:
let userName = "Alice";
userName = 42; // No error during assignment, but this might break the code later.
function greetUser(name) {
console.log("Hello, " + name.toUpperCase()); // Error at runtime if `name` is not a string.
}
greetUser(userName); // Throws an error because `userName` is a number, not a string.
This error can be challenging to debug, as it only surfaces at runtime, making large projects harder to maintain and more prone to bugs.
This is where TypeScript comes into the picture. TypeScript is a programming language that builds on JavaScript by adding static typing. Static typing means you can explicitly specify the types of variables, function arguments, return values, and more. Unlike dynamic typing, where types are determined at runtime, static typing allows TypeScript to catch type-related errors early during development, improving code quality and reducing bugs.
For example, here’s the same code written in TypeScript:
let userName: string = "Alice";
// userName = 42; // Error: Type 'number' is not assignable to type 'string'.
function greetUser(name: string): void {
console.log("Hello, " + name.toUpperCase());
}
greetUser(userName); // Works perfectly since `userName` is correctly typed.