Validate type

2 snippets in TypeScript

TSTypeScript

satisfies Operator

TS · Advanced Types
syntax
const value = expression satisfies Type;
example
type ColorMap = Record<string, string | number[]>;

// Without satisfies: loses specific types
// const colors: ColorMap = { ... } → all values are string | number[]

// With satisfies: validates shape AND keeps specific types
const colors = {
  red: "#ff0000",
  green: [0, 255, 0],
  blue: "#0000ff",
} satisfies ColorMap;

colors.red.toUpperCase();   // OK — TypeScript knows red is string
colors.green.map(c => c);   // OK — TypeScript knows green is number[]
// colors.red.map(c => c);  // Error — string has no .map
output
// satisfies validates compatibility without widening the inferred type

Note Added in TS 4.9. satisfies checks that a value matches a type without changing the inferred type. This gives you the best of both worlds: validation that the shape is correct, plus precise inference of each property. Use it instead of explicit type annotations when you want both safety and specificity.

Type Assertion vs Type Guard

TS · Common Mistakes
syntax
// DANGEROUS: assertion (no runtime check)
const user = data as User;
// SAFE: type guard (runtime check)
if (isUser(data)) { /* data is User */ }
example
interface User {
  id: string;
  name: string;
  email: string;
}

// BAD: assertion — no runtime check, crashes if wrong
const user = JSON.parse(rawJson) as User;
console.log(user.email.toUpperCase()); // Runtime crash if email is missing

// GOOD: type guard — verifies at runtime
function isUser(value: unknown): value is User {
  return (
    typeof value === "object" &&
    value !== null &&
    "id" in value &&
    "name" in value &&
    "email" in value
  );
}

const data = JSON.parse(rawJson);
if (isUser(data)) {
  console.log(data.email.toUpperCase()); // Safe
} else {
  console.error("Invalid user data");
}
output
// Assertions trust you blindly; guards verify at runtime

Note Type assertions (as Type) are a compile-time lie — they produce zero runtime code. Type guards produce actual runtime checks. Always prefer guards for external data (API responses, user input, file reads). Assertions are acceptable for values you genuinely control (e.g., DOM elements you know exist).