JavaScript & TypeScript Flashcards
add an array to an existing array in JS
«array1».push(…«array2»)
deep copy a string to another const in JS
const «variable name» = (‘ ‘ + «string»).slice(1)
what are the primitive types in TS?
» undefined » null » any » boolean » number » string
declare a variable’s type in TS
«variable»: «type»
what are the complex types in TS?
» void » never » Array » object » enum » tuple
declare an enum in TS
enum Color { Red _= 1, Green _= 2, Blue _= 4 }
let c: Color = Color.Green
console.log( Color[2] )
» numbering starts at 0 as a default, set first number to change
declare an array in TS
let fruits: string[] = [‘apple’, ‘orange’, ‘banana’]
let fruits: Array = [‘apple’, ‘orange’, ‘banana’]
declare a tuple in TS
let coordinates: [number, number]
when to declare type void in TS?
function warnUser(): void { console.log('This is my warning message'); }
» for functions that don’t return a value
when to declare type never in TS?
function error(message: string): never { throw new Error(message); }
» for functions that always throw errors ------------------------ function infiniteLoop(): never { while (true) {} }
» for functions that never return
cast variable as type in TS
«variable» as «type»
» only AS syntax is valid in JSX
what is an interface in TS?
» a name for a data structure
declare an interface in TS
interface «object interface name» { «prop1»: «type» «prop2»?: «type» » optional readonly «prop3»: «type» » readonly }
» readonly value is set only in assignment
declare a function interface in TS
interface «function name» {
(«param1»: «type», «param2»: «type»): «return type»
}
» parameter names do not need to match the implementation names
declare an indexable object interface in TS
interface «object name» {
_readonly [«index name»: number | string]: «index value type»
«_another prop1»: «property type»
}
» property type must be subset of index value type
» readonly value is only set in assignment
interpolate string in JS
I am ${«age»} years old
parse JSON string in JS
JSON.parse(«string»)
transform JSON object to string in JS
JSON.stringify(«json»)
difference between normal functions and arrow functions in JS
» arrow functions don’t bind their «this» value