Nâng CaoTypeScript iconTypeScript

Assertion functions trong TypeScript là gì?

Assertion functions có return type asserts condition hoặc asserts param is Type.

Khi function return (không throw), TS assume assertion đúng và narrow type trong phần code tiếp theo.

typescript
function assert(cond: unknown, msg = 'assertion failed'): asserts cond {
  if (!cond) throw new Error(msg);
}

function assertIsString(val: unknown): asserts val is string {
  if (typeof val !== 'string') throw new TypeError();
}

const val: string | undefined = getValue();
assert(val !== undefined, 'val must exist');
val.toUpperCase(); // OK — TS biết val là string (không còn undefined)

Xem toàn bộ TypeScript cùng filter theo level & chủ đề con.

Mở danh sách TypeScript