As keyword

2 snippets in TypeScript

Also written as is keyword

TSTypeScript

Type Assertions

TS · Type Annotations
Syntax
value as Type
<Type>value  // not in JSX files
Example
const rawData = JSON.parse(payload) as { userId: string; role: string };

// HTMLElement narrowing
const canvas = document.getElementById("game") as HTMLCanvasElement;
const ctx = canvas.getContext("2d");

// Double assertion for incompatible types (use sparingly)
const weird = ("hello" as unknown) as number;
Output
// Assertions override the compiler - they do NOT perform runtime conversion

Note Type assertions are a compile-time escape hatch - no runtime checking or conversion happens. If you assert incorrectly, you get silent bugs. Prefer type guards (typeof, instanceof) when possible. The angle-bracket syntax <Type>value conflicts with JSX - always use 'as Type' in .tsx files.

Custom Type Guard Functions

TS · Type Guards & Narrowing
Syntax
function isType(value: ParamType): value is TargetType {
  return /* boolean check */;
}
Example
interface Fish {
  swim: () => void;
  habitat: "water";
}

interface Bird {
  fly: () => void;
  habitat: "air";
}

function isFish(creature: Fish | Bird): creature is Fish {
  return creature.habitat === "water";
}

function move(creature: Fish | Bird) {
  if (isFish(creature)) {
    creature.swim(); // TypeScript knows this is Fish
  } else {
    creature.fly();  // TypeScript knows this is Bird
  }
}
Output
// Custom predicates with 'is' return type enable reusable narrowing

Note The 'value is Type' return annotation is a type predicate - it tells TypeScript to narrow the variable when the function returns true. The compiler trusts your implementation; if your check is wrong, you get silent type errors at runtime. Always keep the check accurate.

Frequently asked questions

How does TypeScript handle as keyword?
TypeScript covers this with 2 copy-ready snippets on this page. The "Type Assertions" snippet in TypeScript uses `value as Type`.
Which code does the TypeScript example use?
The "Type Assertions" snippet uses `value as Type`, from the Type Annotations section of the TypeScript cheat sheet.
What other TypeScript snippets are shown for "as keyword"?
Besides "Type Assertions", this page also shows "Custom Type Guard Functions".
Is there anything to watch out for?
Yes. For "Type Assertions": Type assertions are a compile-time escape hatch - no runtime checking or conversion happens. If you assert incorrectly, you get silent bugs. Prefer type guards (typeof, instanceof) when possible. The angle-bracket syntax <Type>value conflicts with JSX - always use 'as Type' in .tsx files.