Typescript 101 — Typing, Interfaces and Enums oh MY!

What is Typescript?

Let’s get started

Typing Your First Variable

let myFirstVariable: string = "3"
console.log(myFirstVariable)
myFirstVariable = 3
console.log(myFirstVariable)

Typing More Complicated Types

Arrays

const myArray: string[] = ["Hello", "World"]
console.log(myArray)
myArray.push(5)
const myArray: any[] = ["Hello", "World"]
console.log(myArray)
myArray.push(5)
const myArray: Array<string | number> = ["Hello", "World"]
console.log(myArray)
myArray.push(5)

Objects

interface Person {
name: string
age: number
email: string
}
const Alex: Person = { name: "Alex Merced", age: 35 }console.log(Alex)
interface Person {
name: string
age: number
email?: string
}
const Alex: Person = { name: "Alex Merced", age: 35 }console.log(Alex)

Functions

const addNums = (x: number, y: number): number => {
return x + y
}
console.log(addNums(3, 3))
console.log(addNums(3, "3"))

Enum

enum LifeStage {
baby = 1,
toddler,
child,
teenager,
adult,
senior,
}
interface Person {
name: string
height: number
inches: number
stage: number
}
const Alex: Person = {
name: "Alex Merced",
height: 5,
stage: LifeStage.adult,
inches: 10,
}
console.log(Alex)

Custom Types

type yesno = "yes" | "no"
type weirdarray = [string, number, boolean]
type error = "network error" | "schema error"
type success = "success"
type response = error | success
type response = error | success
interface data {
data: Object<any>
}
interface res {
response: response
}
type APIResponse = data & res

Bottom Line

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store