Table of contents
- 1. Start with Type Annotations
- 2. Leverage any Carefully
- 4. Take Advantage of Union and Intersection Types
- 5. Master Type Inference
- 6. Use unknown Instead of any for Safer Code
- 7. Optional Properties and Parameters
- 8. Use Generics to Write Reusable Code
- 9. TypeScript with Arrays and Tuples
- 10. Use Utility Types for Cleaner Code
- Final Thoughts
TypeScript has gained a lot of popularity for its ability to catch bugs early through static typing and make JavaScript code more robust and maintainable. If you're a JavaScript developer making the switch to TypeScript, here are ten essential tips to help you on your journey.
1. Start with Type Annotations
While JavaScript is dynamically typed, TypeScript allows you to explicitly declare types. This is useful to catch type-related bugs early.
let age: number = 27;
let name: string = "Naveen";
This ensures that age
can only hold numbers and name
can only hold strings. Type annotations make your code easier to read and safer.
2. Leverage any
Carefully
In TypeScript, you can define the shape of objects using interface
or type
. This is extremely useful when working with complex objects.
interface User {
name: string;
age: number;
}
const user: User = {
name: "Alice",
age: 25,
};
This helps ensure that any user
object follows the required structure.
4. Take Advantage of Union and Intersection Types
Union types allow you to define a variable that can take multiple types, while intersection types combine multiple types into one.
let status: "success" | "error";
status = "success"; // valid
status = "loading"; // Error
type Admin = { isAdmin: boolean };
type User = { name: string; age: number };
type AdminUser = Admin & User;
Unions make your variables more flexible, while intersections let you combine multiple types.
5. Master Type Inference
TypeScript is smart enough to infer the type based on the value you assign. You don’t always need to specify types explicitly.
let score = 100; // TypeScript infers score as a number
Use type inference to keep your code concise without sacrificing safety.
6. Use unknown
Instead of any
for Safer Code
When you don’t know the type of a value beforehand, it’s better to use unknown
rather than any
. It requires type-checking before you can work with the value.
let input: unknown = "Hello";
if (typeof input === "string") {
console.log(input.toUpperCase());
}
Using unknown
encourages safe type-checking, while any
bypasses this protection.
7. Optional Properties and Parameters
In TypeScript, you can mark properties or function parameters as optional using the ?
symbol.
interface Person {
name: string;
age?: number; // age is optional
}
function greet(person: Person) {
console.log(`Hello, ${person.name}`);
}
Optional parameters allow more flexibility without requiring all values to be present.
8. Use Generics to Write Reusable Code
Generics let you create components that work with various types while preserving type safety.
function identity<T>(value: T): T {
return value;
}
const str = identity<string>("Hello");
const num = identity<number>(42);
Generics allow you to write more reusable and scalable code, especially for libraries and utility functions.
9. TypeScript with Arrays and Tuples
TypeScript lets you define arrays and tuples with specific types, making sure you know what your arrays contain.
let numbers: number[] = [1, 2, 3];
let tuple: [string, number] = ["Alice", 30]; // first element is a string, second is a number
Arrays are great when dealing with homogeneous data, while tuples are useful for heterogeneous data.
10. Use Utility Types for Cleaner Code
TypeScript comes with built-in utility types that make your code cleaner and more concise.
Partial: Makes all properties optional.
Readonly: Makes all properties read-only.
interface Task {
title: string;
completed: boolean;
}
const partialTask: Partial<Task> = { title: "Learn TypeScript" };
const readonlyTask: Readonly<Task> = { title: "Study", completed: false };
// readonlyTask.completed = true; // Error: Cannot assign to 'completed' because it is a read-only property
These utilities help you create variations of existing types without rewriting them.
Final Thoughts
Transitioning from JavaScript to TypeScript can be a game-changer in terms of catching errors early and maintaining a well-structured codebase. Start small, use the tips mentioned above, and gradually adopt more advanced features as you become comfortable with the language.
By adopting TypeScript, you’ll improve the readability, maintainability, and scalability of your code, making your development process more efficient.