Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
学ぶ Object Typing and Type Aliases | Transitioning from JavaScript to TypeScript
TypeScript for JavaScript Developers

bookObject Typing and Type Aliases

メニューを表示するにはスワイプしてください

When you begin using TypeScript, one of the first differences you'll notice from JavaScript is how you can specify the shape of objects directly in your code. Typing object literals allows you to define exactly what properties an object must have, along with their types. This not only helps catch errors early but also improves code readability and maintainability. As your codebase grows, you'll often find yourself working with objects that share the same structure in multiple places. To avoid repeating yourself, TypeScript provides a feature called type aliases, which lets you give a custom name to a specific object shape or any type definition. This makes your code more reusable and easier to manage, especially when dealing with complex objects.

// JavaScript: Defining an object literal
const product = {
  id: 101,
  name: "Laptop",
  price: 999.99
};

// TypeScript: Adding an inline type annotation to the object literal
const product: { id: number; name: string; price: number } = {
  id: 101,
  name: "Laptop",
  price: 999.99
};
// TypeScript: Creating a type alias for a user profile object
type UserProfile = {
  id: number;
  username: string;
  email: string;
  isActive: boolean;
};

// Using the type alias to type-check an API response
const fetchedUser: UserProfile = {
  id: 42,
  username: "alexdev",
  email: "alex@example.com",
  isActive: true
};
12345678910111213141516171819202122
// TypeScript: Using a type alias in function parameters type UserProfile = { id: number; username: string; email: string; isActive: boolean; }; function sendWelcomeEmail(user: UserProfile) { if (user.isActive) { console.log(`Welcome, ${user.username}! Email sent to ${user.email}.`); } } const newUser: UserProfile = { id: 100, username: "jamie", email: "jamie@example.com", isActive: true }; sendWelcomeEmail(newUser);
copy

1. What is a type alias in TypeScript?

2. Why are type aliases useful when working with objects in TypeScript?

question mark

What is a type alias in TypeScript?

正しい答えを選んでください

question mark

Why are type aliases useful when working with objects in TypeScript?

正しい答えを選んでください

すべて明確でしたか?

どのように改善できますか?

フィードバックありがとうございます!

セクション 1.  6

AIに質問する

expand

AIに質問する

ChatGPT

何でも質問するか、提案された質問の1つを試してチャットを始めてください

セクション 1.  6
some-alt