Basic types and inference
Annotating variables
Add : type after a variable name:
The primitive types match JavaScript's: string, number (integers and decimals), boolean, null, undefined, bigint and symbol.
Type inference: let TypeScript work it out
You don't need to annotate everything. TypeScript infers types from values:
Rule of thumb: let TypeScript infer the types of local variables. Add annotations to function parameters, return types of public functions, and anywhere the inferred type isn't what you want.
Arrays
any: the escape hatch (avoid it)
any switches type checking off for a value. Anything goes, so bugs slip through:
That example compiles but crashes when run. Use any only as a temporary measure while migrating JavaScript code.
unknown: the safe "anything"
unknown also accepts any value, but you must check its type before using it:
Use unknown for data from outside your program: JSON from an API, user input, catch errors.
void and never
voidmeans "this function doesn't return a value".nevermeans "this can never happen": a function that always throws, or an impossible branch. You'll see why it's useful in the narrowing lesson.
Type assertions with as
Sometimes you know more than TypeScript. An assertion tells the compiler to trust you:
⚠️ Assertions don't check anything at runtime. If you're wrong, you'll crash. Prefer real checks (narrowing), or a validation library like Zod for external data.
Practice
Add types so that every line marked ✗ produces an error and every ✓ line compiles. Don't use any.
1.What type does TypeScript infer for let total = 0?
2.What's the difference between any and unknown?