Trong khóa JavaScript bạn đã dùng thành thạo Promise, async/await, Promise.all. TypeScript không thêm cú pháp mới nào cho bất đồng bộ — nó chỉ gắn kiểu cho giá trị mà Promise sẽ trả về, và bắt bạn xử lý lỗi cẩn thận hơn.
Promise<T>: kiểu của giá trị trong tương laiHàm async luôn trả về Promise<...>, kể cả khi bạn return một giá trị thường:
interface User {
id: number;
name: string;
}
async function getUser(id: number): Promise<User> {
const res = await fetch(`https://api.example.com/users/${id}`);
if (!res.ok) throw new Error(`HTTP ${res.status}`);
return (await res.json()) as User; // res.json() trả về Promise<any>
}
const user = await getUser(1); // user: UserWARNING
res.json() trả về any, nên as User chỉ là lời hứa của bạn với compiler, không phải kiểm tra thật. Bài tiếp theo sẽ chỉ cách kiểm tra dữ liệu runtime đúng nghĩa.
Viết async function f(): User là lỗi — kiểu trả về của hàm async phải là Promise<User>. Nếu bạn bỏ chú thích, TypeScript tự suy ra Promise<User>.
Awaited<T>: "mở hộp" PromiseAwaited<T> là utility type mô phỏng đúng việc await làm: bóc mọi lớp Promise lồng nhau.
type A = Awaited<Promise<string>>; // string
type B = Awaited<Promise<Promise<number>>>; // number
type C = Awaited<boolean>; // boolean
// Kiểu dữ liệu một hàm async trả về, không cần khai báo lại:
type UserResultNhờ Awaited, Promise.all giữ đúng kiểu từng phần tử của tuple:
const [user, posts] = await Promise.all([
getUser(1), // Promise<User>
Promise.resolve([]) as Promise<string[]>,
]);
// user: User, posts: string[]Kiểu hàm trả về Promise viết như mọi kiểu hàm khác:
type Task<T> = () => Promise<T>;
async function withRetry<T>(task: Task<T>, times = 3): Promise<T> {
for (let
TIP
Trong try, hãy viết return await task() thay vì return task(): chỉ khi await thì lỗi của Promise mới rơi vào catch của chính hàm đó.
catch nhận unknown, không phải ErrorJavaScript cho phép throw bất cứ thứ gì: chuỗi, số, object, undefined. Vì vậy với strict: true (mặc định từ TS 6.0, nhờ cờ useUnknownInCatchVariables), biến trong catch có kiểu unknown:
try {
await getUser(1);
} catch (err) {
console.log(err.message); // ❌ 'err' is of type 'unknown'
if (err instanceof Error) {
console.log(err.message); // ✅ err: Error
} else {
console.log(String(err));
Mẫu hàm tiện ích hay dùng:
function errorMessage(err: unknown): string {
return err instanceof Error ? err.message : String(err);
}Tương tự, reason của Promise.allSettled cũng là any/unknown — luôn narrow trước khi dùng.
const results = await Promise.allSettled([getUser(1), getUser(2)]);
for (const r of results) {
if (r.status === "fulfilled") console.log(r.value.name); // r.value: User
else console.log(errorMessage
r.status là discriminant — đúng kỹ thuật discriminated union bạn đã học ở chương 4.
awaitMột lỗi kinh điển: gọi hàm async mà quên await. TypeScript bắt được nhiều trường hợp:
const user = getUser(1);
console.log(user.name); // ❌ Property 'name' does not exist on type 'Promise<User>'
if (getUser(1)) { } // ❌ This condition will always return true since this 'Promise<User>' is always definedVới Promise "thả trôi" (saveLog(); không ai await), compiler không báo — hãy bật rule @typescript-eslint/no-floating-promises (chương 12).
| Bạn muốn | Viết |
|---|---|
| Kiểu trả về hàm async | Promise<T> |
Kiểu giá trị sau await | Awaited<T> |
| Kiểu kết quả của hàm async có sẵn | Awaited<ReturnType<typeof fn>> |
Xử lý lỗi trong catch | err: unknown → instanceof Error |
Comments