Common TypeScript Types

·

1 min read

TypeScript is JavaScript with syntax for types.

Here are some common types and how we could use them:

// number
function add(a: number, b: number): number {
  return a + b
}

// string and boolean
function isStrLengthGreaterThan(str: string, len: number): boolean {
  return str.length > len
}

// interface
interface Person {
  name: string;
  age: number;
  email?: string; 
};

let person: Person = {
  name: 'B',
  age: 28,
  email: 'bz@gmail.com'
};

// array of numbers
let number: number[] = [1, 2, 3, 4, 5];

// tuple with two values of different types, which enforces both types and order
let tuple:[string, number] = ['BZ', 28];


// enum with three values, limiting options
enum Colors {
  Red,
  Green,
  Blue
}

// union type that can be either a number or a string or another type
let unionType: string | number | boolean = 'hello';
unionType = 123;
unionType = true;

// union type array that allows more than one types in the same array
let unionTypeArr: (string | number)[] = [1, '2', 3];

// the array below can have elements that either are all numbers or all strings
let unionTypeArr2: string[] | number[] = ['1', '2', '3'];

// alias for a reusable user-defined type
type alphanum = string | number;
let someVariable: alphanum = 12;
someVariable = '12';