Course outline · 0% complete

0/26 lessons0%

Course overview →

Literal Types, any, and unknown

lesson 2-3 · ~12 min · 6/26

Types can be exact values

A literal type is a type with exactly one allowed value. "left" (the type) accepts only "left" (the string). Alone that is not useful, but combined with | (or) it models a fixed menu of options:

let direction: "left" | "right" = "left";
direction = "right"; // fine
direction = "up";    // error: not assignable

Compare the JavaScript habit of passing magic strings and hoping nobody misspells "rigth". The | symbol builds a union type, and Unit 4 is devoted to it. For now, remember: strings and numbers themselves can be types, and a union of literals is TypeScript's built-in answer to "one of these exact values".

Code exercise · typescript

Run it. Then try assigning direction = "up" and run again, the compiler lists the two allowed values in its error.

any and unknown: checking off vs. checking kept on

Two special types describe "could be anything", with opposite safety:

anyunknown
Assign anything to ityesyes
Call methods on ityes, uncheckedno, error
Type checkingswitched offstill on

any turns the compiler off for that value: x.foo.bar() compiles and crashes at runtime, the exact bugs you came here to escape. unknown also accepts any value, but keeps checking on: every use is an error until you prove what the value is, with a check like typeof value === "string".

When does a value genuinely have an unknowable type? When it comes from outside your program. The classic source is a web API — a program on another server that yours sends a request to over the network and gets data back from, usually as JSON text. JSON.parse turns that text into a value, but nothing guarantees the other server sent the shape you expect. Type the result unknown and prove its shape before use; Unit 7 builds that full pattern.

anychecks OFFx.anything() compilescrashes at runtimeunknownchecks still ONmust prove the type firstthen use it safely
any silences the compiler entirely. unknown accepts any value but keeps every check active until you narrow it.

Code exercise · typescript

This function takes unknown and proves the value is a string before touching .length. Run it, then try moving the return "a string..." line above the if to see the compiler refuse.

Code exercise · typescript

Your turn. Write flip(state: "on" | "off"): "on" | "off" that returns the other value. Then declare bulb starting at "off", flip it twice, and print "bulb is " + bulb after each flip.

Quiz

Your program parses text it received from a web API (another server answering your program's request) with JSON.parse, and you do not yet know the shape. Which type should the variable have?