Typescript basics
1. What is TypeScript?
Think of TypeScript as an improved version of JavaScript. It helps developers write better and more reliable code by adding a feature called "static typing," which means we can specify the types of values in our code.
Example:
// JavaScript code function add(x, y) { return x + y; } // TypeScript code with type annotations function add(x: number, y: number): number { return x + y; }
2. Setting Up TypeScript
To use TypeScript, we need to install it on our computer. We can do this by running a simple command. Once installed, write the code in files with a .ts
extension and then use a tool to convert it into regular JavaScript.
Example:
# Install TypeScript globally npm install -g typescript # Create a TypeScript file (e.g., yourfile.ts) # Compile it into JavaScript using the tsc command tsc yourfile.ts
3. Type Annotations and Inference
In TypeScript, we can say what type (like a number or text) a variable should be. For example, if we have a variable storing an age, we can explicitly say it's a number. TypeScript can also figure out the types on its own in many cases.
Example:
// Type annotations let age: number =25; let name: string = "John"; // Type inference let isAdmin = false; // TypeScript knows this is a boolean
4. Interfaces
Interfaces are like rules for how an object should look. If we say an object should have a name and an age, TypeScript makes sure us follow these rules when creating or using that object.
Example:
// Interface defining the structure of a person interface Person { name: string; age: number; } // Using the interface to create an object let user: Person = { name: "Alice", age: 30, };
5.Enums
Enums help us define a set of names for things. For instance, if we're working with colors, we can create an enum with names like Red, Green, and Blue, making your code more readable.
Example:
// Enum defining colors enum Color { Red, Green, Blue, } // Using the enum let myColor: Color = Color.Green;
These examples should provide a practical understanding of how TypeScript works and how it can improve the development process.
Comments
Post a Comment