Basics of TypeScript - nuthanc/microservice GitHub Wiki

TypeScript

TypeScript Overview

First App

  • fetchjson

Syntax and Design pattern

Second App

  • Features

Type Annotations and Inference

// Annotations: We telling typescript
const apples: number = 5; // Annotations can be removed as it is automatically added by Inference
let colors: string[] = ['red', 'green']

// Object literal
let point: { x: number; y: number} = {
  x: 10,
  y: 20
}

// Function 
// till void is the annotation where void is the return type
const logNumber: (i: number) => void = (i: number) => {
  console.log(i);
}
  • Understanding Inferences
  • D 5-inference: Declaration and Initialization on the same line, annotations not required
  • D 6-inf
const json = '{"x": 10, "y": 20}';
const coordinates = JSON.parse(json); //coordinates is any when hovered
console.log(coordintaes); // {x: 10, y: 20}
  • D 9-json, 8-any
const json = '{"x": 10, "y": 20}';
const coordinates: { x: number, y: number} = JSON.parse(json); //coordinates is any when hovered
console.log(coordintaes); // {x: 10, y: 20}
  • D 11-func
const add = (a: number, b: number): number => {
  return a+b;
}

Inference around Functions

  • Github link: https://github.com/nuthanc/typescriptcasts
  • features directory annotations functions.ts
  • D 9-functions,copy-of-9
  • We add annotations for return type also even though inference can be used because when we forget to return something, inference will make it void

Annotations to Anonymous Functions

  • functions.ts

Void and Never

  • functions.ts

Destructuring with Annotations

  • functions.ts

Annotations Around Objects

  • objects.ts

Arrays in Typescript

Tuples in Typescript

  • D 2-tuples, 8-def, 5-tuples, 7-pos
  • tuples.ts in features
  • Type alias

Interfaces

Classes