Skip to content

Instantly share code, notes, and snippets.

@shivam1283
Last active July 16, 2021 19:14
Show Gist options
  • Save shivam1283/d1cc0fa54add57a8a1fadc3f4e81a6c8 to your computer and use it in GitHub Desktop.
Save shivam1283/d1cc0fa54add57a8a1fadc3f4e81a6c8 to your computer and use it in GitHub Desktop.
[TS tutorial] Notes #react #js #ts

Initial

  1. install tsc compliler
  2. npm install -g typescript
  3. create a folder with an index.html
  4. npm init
  5. npm install --save-dev liteserver
  6. create index.ts
  7. run tsc index.ts

To automatically reload

Method 1 (whole project):

  • tsc init
  • Using VS Code
    • command + shift + b
    • select tsc:watch
  • Using CLI
    • tsc -w

Method 2 (single file):

  1. tsc index.ts -w : enables watch mode

Core Types

number

Common in JS and TS.

string

'', "", ``

boolean

true and false

object

The basic structure is defined i.e. the permissible keys and their respective types.

array

let a : string[] a = [12]
above statement will throw an error
let a: any[] a= [12,'aa']
above statement will not throw an error An array can be flexible as well as strict

tuples

An array of fixed size and fixed type of each element.

let a: [string,number]; a = [1,'sad']; a = [2,'ad','sds'];

enum

enum a {AUTHOR = 1 , EDITOR = 2 , DIRECTOR = 3}

union type

let account : number | string

literal (variable name) type

const a = 12
the type of a is 12

  • The types based on core types, like '12' itself can be a type of a variable whose value can only be 12.

alias type

type combinedTypes = number | string type stringValues = 'as-text' | 'as-number'

function return type and void

function sum(n1 : number, n2: number):number
the returned values by function are of number type

function type

let f : Function

function a(n1: number, n2: number, cb: (a:number) => void)

unknkown type

let x : unknown

Type inference

Where tsc automatically infers the type of the variable without explicitely assigning a type. For eg let a = 1

a: number is infered by tsc

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment