free beginners typescript course by Matt Pocock
Matts a good teacher and an expert on typescript. He released a free typescript beginners course and I wanted to check it out.
18 exercises in all and you can complete the exercises in the browser. It's basics but listen to the solutions videos and you'll always pickup something new from Matt
- with typescript you're declaring the contract and when using typescript think about where you want the contract to be (contract enforcement), thus when declare variables make sure they match the contract
- union type: you OR e.g. a | b | c // a or b or c "everywhere in typescript", "define types of data flowing through your app"
- intersects: you combine type e.g. a & b & c // all 3 combined as a new type
- specifying arrays, 2 ways 1. square brackets (Posts[]) or generics Array<Post>
- lesson 9 and onwards gets more interesting
- return type of a fn which returns a Promise should be a Promise which wraps what will be resolved e.g. Promise<Person>
- but could also type the response e.g. const data: Person = await fetch(....)
- that typing is preferable to casting using "as"
- define key and value of a map: const cache: { [id: string]: string } = { "1": "apples", "2": "oranges" };
- you can also use built in Record e.g. const cache: Record<string, string> = {};
- use typeof to narrow down what a variable is e.g. if (typeof amount === 'object') { ...its an object }
- typing a try catch: could cast inside catch e.g. (e as Error).message
- - but better is to do inside catch if (e instanceof Error) return e.message
- typing functions
type FocusListener = (isFocussed: boolean) => void
const addListener = (onFocusChanged: FocusListener) => {
}
- when type a function to return void means you don't have to return anything, if typed return as undefined then would need to return undefined
reminder: access autocomplete in vscode using ctrl + space
Comments
Post a Comment