TExcelTAD
Home › TypeScript › TS Special Types

TypeScript Special Types

Besides the primitives, TypeScript has a few types that don't describe ordinary values. They describe how much the compiler knows about a value: everything (any turns checking off), something unknown (unknown), or no possible value at all (never). There is also void for functions that return nothing, plus undefined and null.

any — switch off type checking

A value of type any can be anything, and the compiler lets you do anything with it: call it, read any property, assign it anywhere. That makes any an escape hatch — and a dangerous one:

ts · try it yourself
let data: any = "hello";
data = 42;
data = { nested: true };

const n: number = data;        // no error, even though data is an object
console.log(n * 2);            // "number" arithmetic on an object
console.log(data.nested);
console.log(data.toFixed);     // a method that doesn't exist - no complaint
NaN
true
undefined

TypeScript happily compiled this program, even though n is not a number at all and data.toFixed doesn't exist. Calling data.toFixed(2) would crash at runtime. any spreads, too: anything you read from an any value is also any.

Tip: Treat any as a temporary measure when migrating JavaScript. The strict setting forbids implicit any; you only get it when you write it on purpose.

unknown — the safe alternative

unknown also accepts any value, but you can't use it until you check what it is. This is perfect for data from outside your program: JSON, user input, catch blocks.

ts · try it yourself
let input: unknown = JSON.parse('{"title": "Notes"}');

console.log(input.title);
main.ts(3,13): error TS18046: 'input' is of type 'unknown'.

Narrow it first with a runtime check, and TypeScript allows the access:

ts · try it yourself
function describe(value: unknown): string {
  if (typeof value === "string") {
    return `string of length ${value.length}`;
  }
  if (typeof value === "number") {
    return `number ${value.toFixed(2)}`;
  }
  if (typeof value === "object" && value !== null && "title" in value) {
    return `object titled ${String(value.title)}`;
  }
  return "something else";
}

console.log(describe("abc"));
console.log(describe(3.14159));
console.log(describe(JSON.parse('{"title": "Notes"}')));
console.log(describe(true));
string of length 3
number 3.14
object titled Notes
something else
any unknown
Can hold any value yes yes
Can be assigned to other types yes only to unknown/any
Can read properties / call it yes, unchecked no, narrow it first
Safe no yes

never — no value at all

never is the type of something that cannot happen. A function that always throws, or loops forever, has return type never, because it never returns normally:

ts · try it yourself
function fail(message: string): never {
  throw new Error(message);
}

function parseAge(text: string): number {
  const n = Number(text);
  if (Number.isNaN(n)) {
    fail(`not a number: ${text}`);
  }
  return n;
}

try {
  console.log(parseAge("31"));
  console.log(parseAge("abc"));
} catch (err) {
  console.log((err as Error).message);
}
31
not a number: abc

never is also what remains when every possibility has been ruled out. That makes it great for exhaustiveness checks — if you later add a new case and forget to handle it, the assignment to never fails:

ts · try it yourself
type Light = "red" | "yellow" | "green";

function action(light: Light): string {
  switch (light) {
    case "red":
      return "stop";
    case "green":
      return "go";
    default:
      const unhandled: never = light;
      return unhandled;
  }
}
main.ts(10,13): error TS2322: Type '"yellow"' is not assignable to type 'never'.

The compiler noticed that the literal type "yellow" reaches the default branch. Add case "yellow": return "slow down"; and the error disappears. You'll use this pattern a lot with discriminated unions.

void — "returns nothing useful"

void is the return type of functions that don't return a value. It's usually inferred:

ts · try it yourself
function logLine(text: string): void {
  console.log(`> ${text}`);
}

const result = logLine("saved");
console.log(result);
> saved
undefined

At runtime such a function returns undefined, but void tells readers "don't use the result".

undefined and null

undefined and null are both types and values. In strict mode they are only allowed where the type says so — string | undefined, number | null and so on. The Null & Undefined lesson covers them in depth.

Test yourself

Which type accepts any value but forces you to check it before use?

  1. any
  2. unknown
  3. never
  4. object

What is the return type of a function that always throws?

  1. void
  2. undefined
  3. never
  4. null

Why is any considered risky?

  1. It makes programs slower
  2. It disables type checking for that value and everything derived from it
  3. It cannot hold objects
  4. It is removed in strict mode