𝗙𝗿𝗼𝗺 𝗭𝗲𝗿𝗼 𝘁𝗼 𝗛𝗲𝗿𝗼 𝗶𝗻 𝗧𝘆𝗽𝗲𝗦𝗰𝗿𝗶𝗽𝘁
TypeScript makes your JavaScript code safer and easier to manage. It helps you find errors early.
TypeScript adds static typing to JavaScript. It turns into plain JavaScript when you run it.
Common basic types:
- number: for all numbers
- boolean: true or false
- string: for text
- symbol: for unique IDs
- bigint: for very large numbers
Type Annotations: let name: string = "Alice"; let age: number = 30;
Arrays and Objects: let fruits: string[] = ["apple", "banana"]; let user: { name: string; age: number } = { name: "Bob", age: 25 };
Functions: function greet(name: string): string { return "Hello, " + name; }
Use void if a function returns nothing: function logMessage(): void { console.log("Message sent"); }
Advanced Tools:
- Type Aliases: Create your own types.
- Interfaces: Define the shape of objects.
- Enums: Use a set of named constants.
- Tuples: Fixed length arrays with specific types.
- Generics: Create reusable code that works with many types.
- Utility Types: Use Partial, Pick, or Record to modify types.
Best practices for your workflow:
- Use type for simple aliases and primitives.
- Use interface for object shapes.
- Avoid using any. It breaks the safety of your code.
- Use unknown if you do not know the type yet.
- Let the compiler guess types when it is obvious.
- Add annotations to your APIs for clarity.
Mastering these tools helps you build large, stable applications.
Source: https://dev.to/miasalazar/from-zero-to-hero-in-typescript-425j