On this page
is
Prev: `readonly` | Up: builtins | Next: `asserts`
Rel: builtins, Structural Typing & Narrowing
Ref: TypeScript Docs — is
Tags: #public #web #typescript #builtins #tier/standard
Syntax & Overview
function isString(v: unknown): v is string { return typeof v === 'string'; }
User-defined type guard return annotation that narrows a parameter's type in the calling scope when the function returns true.
Notes & Pitfalls
- User-defined type guard (
param is Type): Essential for narrowingArray.prototype.filter()results (items.filter(isNonNull)). - Compiler does not verify the body: Ensure your runtime check genuinely matches the declared type.
Example
interface Cat { meow(): void }
interface Dog { bark(): void }
function isCat(pet: Cat | Dog): pet is Cat {
return "meow" in pet;
}
function speak(pet: Cat | Dog) {
if (isCat(pet)) pet.meow();
else pet.bark();
}
Linked from
Related notes
- tuts/typescript/builtins/asserts Linked here; links to this page; shared tags: #builtins, #tier, #typescript, #web
- tuts/typescript/builtins/readonly Linked here; links to this page; shared tags: #builtins, #tier, #typescript, #web
- tuts/typescript/builtins Linked here; links to this page; shared tags: #builtins, #typescript, #web
- tuts/typescript/type_system/structural_typing_and_narrowing Linked here; links to this page; shared tags: #typescript, #web
- tuts/typescript/tutorials/type_safe_api_clients_and_validation links to this page; shared tags: #typescript, #web
- tuts/typescript/builtins/any shared tags: #builtins, #tier, #typescript, #web
- tuts/typescript/builtins/as_const shared tags: #builtins, #tier, #typescript, #web
- tuts/typescript/builtins/enum shared tags: #builtins, #tier, #typescript, #web
- tuts/typescript/builtins/infer shared tags: #builtins, #tier, #typescript, #web
- tuts/typescript/builtins/keyof shared tags: #builtins, #tier, #typescript, #web