Typescript - Basics

Typescript Basics

Using Types

Core Types

  • number

  • string

  • boolean

  • object

  • tuple

  • Enum

  • Javascript uses “dynamic types” (resolved at runtime), versus Typescript uses “static types” (set during development). Regular javascript doesn’t include any time assignment.

  • In TypeScript, you work with types like string or number all the times. The core primitive types in TypeScript are all lowercase!

  • OBject types can also be created for nested objects

  • Type aliases can be used to “create” your own types.

type User = { name: string; age: number };
const u1: User = { name: 'Max', age: 30 }; // this works!

Using Type Alias to simplify Code

type User = { name: string; age: number };
 
function greet(user: User) {
  console.log('Hi, I am ' + user.name);
}

function isOlder(user: User, checkAge: number) {
  return checkAge > user.age;
}
  • Function types define the parameter and return type of a function
  • Function Type allows us to describe which type of function specifically we want to use
  • Type aliases can be used to merge complex types into aliases
  • Literal types and Union types can be used for scenarios where you expect more than one possible types

Object Type


enum Status {ACTIVE, DEACTIVATED, DELETED}

// Using TS Object Inference
const testPerson : {
    name: string,            // string
    age: number,             // number
    hobbies: string[],       // Array
    role: [number, string]   // Tuple
    status: Status           // Enum
}= {
  name: "John Doe",
  age: 30,
  hobbies: ['Sports', 'Cooking'],
  role: [2, 'author'],
  status: Status.ACTIVE
};

Union Type

// Union Type & Literal Type
function combine(
  input1: Combinable,
  input2: number | string,              // Untion Type
  resultType: "as-number" | "as-text"   // Literal Type
) {
  let result: any;
  if (
    typeof input1 === "number" &&
    typeof input2 === "number" &&
    resultType === "as-number"
  ) {
    result = +input1 + +input2;
  } else {
    result = input1.toString() + input2.toString();
  }
  return result;
}

Type Aliases

  • Type aliases can be used to “create” your own type
  • It allows you to avoid unnecessary repetition and manage types centrally.
type User = {name: string, age: number}
const u1: User = { name: 'John', age: 30}

Function Declarations

Inferred Return Type

// Function Return Type by Inference
function add(n1: number, n2: number) {
  return n1 + n2;
}

Defined Return Type

// Defined Return Type
function sec2PrintResult(num: number):void {
  console.log("Result: " + num);
}

Function Expression


// Named Function Expression
const sum = function sum(a: number, b: number) {
  return a+b
}

// Arrow Function
const sum = (a: number, b: number) : number => a + b