Making Typescript Stick
March 23, 2022Making Typescript Stick
Make it stick book --> using to write onboarding
https://www.typescript-training.com/course/making-typescript-stick
// @errors: 2322 2320
let first: string & number;
let second: String & Number;
first = "abc";
second = "abc";
second = new String("abc");
-
When using the primitive types string and number we can see that the union of these two types results in a never. In other words, there is no string that can be also regarded as a number, and no number that can also be regarded as a `string
-
When using the interface types String and Number, we can see that the union does not result in a never
Use the lowercase types as much as possible. They are primitives.
What order do logs print?
function getData() {
console.log("elephant")
const p = new Promise((resolve) => {
console.log("giraffe")
resolve("lion")
console.log("zebra")
})
console.log("koala")
return p
}
a...
dog, cat, elephant, giraffe, zebra, koala, lion, moose
Variadic Tuple Types
enum Sandwich {
Hamburger,
VeggieBurger,
GrilledCheese,
BLT
}
type SandwichOrder = [
number, // order total
Sandwich, // sandwich
...string[] // toppings
]
// ---cut---
/**
* return a...
Example of cleaning types: https://github.com/ReactiveX/rxjs/pull/5859/files
Error type unknown
function somethingRisky() {}
// ---cut---
try {
somethingRisky();
} catch (err: unknown) {
if (err instanceof Error) throw err;
else throw new Error(`${err}`);
}
interface vs. type
// @errors: 2300
type Color = {
red: number;
green: number;
blue: number;
};
interface Color {
alpha: number;
}
Interfaces are open, types are not. Two interfaces would compile.
Learning
https://github.com/type-challenges/type-challenges
// @errors: 2344
type Expect<T extends true> = T
type Equal<X, Y> =
(<T>() => T extends X ? 1 : 2) extends
(<T>() => T extends Y ? 1 : 2) ? true : false
type NotEqual<X, Y> = true extends Equal<X, Y>...