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.