TypeScript for Beginners: A 5-Minute Guidetype
by Hugo Valcourt, Founder, Senior Front-end Developer
1. Setting Up TypeScript
To start with TypeScript, you'll need to install it using Node.js and npm:
bashCopy codenpm install -g typescript
Once installed, you can write TypeScript code in .ts
files and compile it to JavaScript using the TypeScript compiler (tsc
):
bashCopy codetsc filename.ts
2. Basic Type Annotations
TypeScript allows you to declare types for variables, function parameters, and return values. This helps prevent mistakes by ensuring variables hold the expected types.
Example:
typescriptCopy codelet message: string = "Hello, TypeScript!"; // string type let age: number = 25; // number type let isStudent: boolean = true; // boolean type
If you try to assign a wrong type, TypeScript will throw an error:
typescriptCopy codeage = "twenty-five"; // Error: Type 'string' is not assignable to type 'number'.
TypeScript for Beginners: A 5-Minute Guide
TypeScript is a superset of JavaScript that adds static typing to help catch errors early during development. If you're familiar with JavaScript, learning TypeScript is a natural next step. Here’s a quick introduction!
1. Setting Up TypeScript
To start with TypeScript, you'll need to install it using Node.js and npm:bashCopy codenpm install -g typescriptOnce installed, you can write TypeScript code in .ts
files and compile it to JavaScript using the TypeScript compiler (tsc
):bashCopy codetsc filename.ts
2. Basic Type Annotations
TypeScript allows you to declare types for variables, function parameters, and return values. This helps prevent mistakes by ensuring variables hold the expected types.
Example:
typescriptCopy codelet message: string = "Hello, TypeScript!"; // string type let age: number = 25; // number type let isStudent: boolean = true; // boolean typeIf you try to assign a wrong type, TypeScript will throw an error:typescriptCopy codeage = "twenty-five"; // Error: Type 'string' is not assignable to type 'number'.
3. Functions and Type Checking
You can define types for function parameters and return types.
Example:
typescriptCopy codefunction greet(name: string): string {
return `Hello, ${name}!`;
}
greet("Alice"); // works fine
greet(123); // Error: Argument of type 'number' is not assignable to type 'string'.TypeScript ensures that the greet
function only accepts a string
and returns a string
.
4. Type Inference
TypeScript can infer types even when you don’t explicitly declare them.
Example:
typescriptCopy codelet score = 100; // inferred as number score = "high"; // Error: Type 'string' is not assignable to type 'number'.
5. Interfaces
Interfaces define the structure of an object. They’re like contracts for what an object should look like.
Example:
typescriptCopy codeinterface Person { name: string; age: number; isStudent: boolean; } const user: Person = { name: "Bob", age: 22, isStudent: true, };
Now, if you try to omit or add extra properties, TypeScript will throw an error.
6. Classes
TypeScript also supports object-oriented programming with classes.
Example:
typescriptCopy codeclass Car { model: string; year: number; constructor(model: string, year: number) { this.model = model; this.year = year; } displayInfo(): void { console.log(`${this.model} was built in ${this.year}.`); } } const myCar = new Car("Toyota", 2020); myCar.displayInfo(); // Toyota was built in 2020.
7. Generics
Generics allow you to create reusable components that work with different types.
Example:
typescriptCopy codefunction identity<T>(value: T): T { return value; } console.log(identity<string>("TypeScript")); console.log(identity<number>(42));
The function identity
can take a value of any type, and TypeScript will ensure that the returned type matches.
8. Union Types
Union types let a variable or parameter hold more than one type.
Example:
typescriptCopy codelet value: string | number; value = "Hello"; value = 123; // value = true; // Error: Type 'boolean' is not assignable to type 'string | number'.
9. Optional Properties
You can mark properties as optional using the ?
operator.
Example:
typescriptCopy codeinterface User { username: string; email?: string; // optional } const user1: User = { username: "Alice" }; const user2: User = { username: "Bob", email: "bob@example.com" };
10. Compiling and Running TypeScript
You can compile TypeScript to JavaScript using:
bashCopy codetsc filename.ts
This generates a .js
file that you can run using Node.js or in the browser.
Conclusion
TypeScript enhances JavaScript by introducing types, making your code safer and more maintainable. In these 5 minutes, you’ve learned how to:
Use basic type annotations.
Write functions with type checking.
Use interfaces and classes.
Work with generics and union types.
Ready to dive deeper? Keep practicing!