Typescript
JavaScript with types
2023-01-27
Notes
-
Default target is ES3, pretty old. Use
--target es2015for browsers, and--target esnextfor servers. -
Good to have
noImplicitAnyandstrictNullCheckson. -
Always prefer using
interfaceovertypeunless explicitly needed.- The former is extendable and mergable
- It shows up by name in error messages.
typecan alias existing types (or interfaces):type Username = string | IUsername.type ColorAndCircle = Color & Circleis an intersection of two interfaces.
Exhaustive Type Checking
Consider an enum:
enum Color {
Red,
Blue,
Green,
}
that has a switch case:
function whichColor(c: Color): string {
switch (c) {
case Color.Red:
return "Red";
case Color.Blue:
return "Blue";
default:
return "Unknown color";
}
}
but we missed Color.Green and yet no compiler errors!
A simple solution (Typescript 4.9+):
function whichColor(c: Color): string {
switch (c) {
case Color.Red:
return "Red";
case Color.Blue:
return "Blue";
default:
c satisfies never;
return "Unknown color";
}
}
Which leads to:
Type ‘Color.Green’ does not satisfy the expected type ‘never’.