Trial by TypeScript
Original slide content, adapted from the source deck into static cards.
- 01
Trial by TypeScript
@charlespeters
- 02
So TypeScript.
- 03
Who's using TypeScript?
- Storybook
- Yarn version 2
- MobX State Tree
- Apollo
- Next.js
- Prisma
- Jest
- Framer Motion
- Ember.js
- Cycle.js
- Rx.js
- Visual Studio Code
- 04
TypeScript is a superset of JavaScript to bring strong typing to our beloved untyped language
- 05
The advantage of a strongly typed language is that you are forced to make the behaviour of your program explicit. This makes code easier to understand because there is less hidden behaviour. However, it also makes your code more verbose.
- 06
TypeScript as a language is JavaScript with bolted on type annotations to bring strong typing to JavaScript.
- 07
From a learning experience, TypeScript becomes much easier when you consider it taking notes about the code you were already writing
- 08
Demo
codepen.io/charliewilco/pen/qzGQKz
- 09
function getCurrency(amount) { return amount.toLocaleString("en", { style: "currency", currency: "USD", }); } getCurrency(5000); // $5000.00 - 10
getCurrency("5000"); // "5000" getCurrency(); // TypeError: Cannot read property 'toLocaleString' of undefined getCurrency([5000, 4000]); - 11
But with TypeScript...
function getCurrency(amount: number): string { return amount.toLocaleString("en", { style: "currency", currency: "USD", }); } - 12
Basic Types
- number
- string
- boolean
- string[] or Array<string>
- Promise<>
- void
- any
- Union type string | null
- 13
Interfaces
A definition for the shape for anything object related, like classes
interface LabeledValue { label: string; size: number; } function printLabel(labeledObj: LabeledValue): void { console.log(labeledObj.label); } printLabel({ size: 10, label: "Size 10 Object" }); - 14
Generics
function createArray<T>(item: T, count: number): T[] { return Array(count).fill(item); } createArray<string>("thing", 5); createArray<LabeledValue>( { size: 10, label: "Size 10 Object", }, 5, ); - 15
class LocalCache<T> { public items: T[] = []; add(item: T): void { this.items.push(item); } remove(item: T): void { const key: number = this.items.find(item); if (key) { this.items.splice(key, 0); } } } - 16
const cache = new Cache<string>(); cache.add("Hello"); cache.remove("Hello"); - 17
Enums
enum ThemeType { BLUE = "BLUE", GREEN = "GREEN", RED = "RED", } - 18
function getTheme(theme: ThemeType) { switch (theme) { case ThemeType.BLUE: return {...} case ThemeType.RED: return {...} default: throw new Error("Never gonna die!!!") } } - 19
getTheme("BLUE"); // no getTheme(ThemeType.BLUE); // yes - 20
Enough syntax, Charles.