Typescript basics part 1

 What I learned today: Refreshing some Typescript basics since I haven't touched it in awhile :)

TypeScript is a superset of JavaScript that adds static typing to the language. It takes typescript code and transcompiles to JavaScript.



Here I set the type of variable 'num' to number. If I try to assign a string, it gives me an error. If I tr to compile this, It will compile the ts file into a js file and return this error:


We can create a tsconfig.json file by using 'tsc --init'. There are a number of useful options in tsconfig specifically 'rootdir' and 'outdir'. With this we can configure where our source typescript files are and where our javascript files will compile to.



Here we can see that now when we compile using 'tsc' command, all the typescript files will be pulled from the './src' directory and all the compiled javascript files will go to the './dist' directory.

We can assign any type to a variable by doing:

let y: any = "hello"

We can assign types to an array:

let person : [number, string, boolean] = [1, 'a', false]

We can also do an array of arrays by using tuples:

let people : [number, string][]
people = [
    [1, "John"],
    [2, "Steve"]
]

Unions allow us to do multiple types:

let random : string | number = 3
random = "hello"

Enums allow us to name defined constants

enum Direction1 {
    Up = 1,
    Down = 2
}

We can define objects:

const user : {
    id: Number,
    name: String,
} = {
    id: 1,
    name: "Joe"
}













Comments

Popular posts from this blog

Lifecycle of React components

Styled Components

e-commerce website built with React.nodejs