Now that you understand the TypeScript basics, let’s see how to convert some common JavaScript code to TypeScript.
Typing Objects
JavaScript:
const product = {
id: 10,
name: "Book",
price: 99,
};
TypeScript:
interface Product {
id: number;
name: string;
price: number;
}
const product: Product = {
id: 10,
name: "Book",
price: 99,
};
From JavaScript fetch() to TypeScript
JavaScript:
// Fetching user data
async function getUser(id) {
const response = await fetch(`/api/users/${id}`);
const user = await response.json();
return user;
}
// Creating a user
async function createUser(userData) {
const response = await fetch("/api/users", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(userData),
});
return response.json();
}
TypeScript:
// Define the shape of your data
interface User {
id: number;
name: string;
email: string;
}
interface CreateUserData {
name: string;
email: string;
}
// Type your functions
async function getUser(id: number): Promise<User> {
const response = await fetch(`/api/users/${id}`);
const user = await response.json();
return user;
}
async function createUser(userData: CreateUserData): Promise<User> {
const response = await fetch("/api/users", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(userData),
});
const user = await response.json();
return user;
}