Thursday, April 15, 2021
TYPESCRIPt NOTES
TYPES
Primitive
- String
- Bool
- Number
SPECIAL
- Arrays
- Any
- Function params and props
- Objects
Declaring Type Example Todo
type Todo = {
id: number,
text: string,
done: boolean,
SKELETON
- FUNCTION
• Function(param:<type>) : <Return Type> {
return
1
Thursday, April 15, 2021
Mapped Keywords
ReadOnly=> prevents modifying {makes all props in
object readonly}. ReadOnly<…>
type Todo = ReadOnly<{
id: number,
text: string,
done: boolean,
}>
Literal Types
done: true
Arrays in function syntax
fx(x:X[]) : X[]
TYPEOF GUARDS
• "string"
• "number"
• "bigint"
• "boolean"
• "symbol"
• "unde ned"
• "object"
• "function"
2
fi
Thursday, April 15, 2021
INTERSECTING TYPES & TYPE OPERATORS
type = A & B.
JOINS both types into new type
UNIONS
type foo = number | string
const a: Foo = 1
const a: Foo = “home”
FOO TYPE CAN BE EITHER A NUMBER OR STRING
Use typeof in an if else statement to narrow union
OPTIONAL
? After property for optional
INTERFACE - explicitly describe the object or class shape
interface User {
name: string;
id: number;
}
Type Aliases
SAME AS INTERFACE BUT CAN’T BE RE-OPENED/CHANGED
ENUMS
NUMBERS—auto increment
enum Direction {
Up = 1,
Down //2
Left//3
Right//4
STRINGS—> good for debugging
enum Directions {
Up = “UP”,
Thursday, April 15, 2021
Down = “DOWN”,
Left = “LEFT”,
Right = “RIGHT”
TYPE ASSERTIONS
Var foo = <foo>bar;
IN REACT/JSX
Var foo = bar as foo