Types

“locking” a variable definition to a particular kind of variable (number, string, etc.)

TypeScript has a small number of built-in types, including

  • Number

  • String

  • Boolean

  • Array

  • Enum

  • Void

Basic Type Example

Types can create clearer code and prevent errors

function timesTwo( n : number ) : number { 
    return n * 2 
};

timesTwo(“6”); // compile-time error
var multiplied : string = timesTwo(5); // compile-time error
var num:number = timesTwo(5); // Correct

Number

The number type can be set to any number

String

The string type can be any string – i.e., any sequence of Unicode characters

Boolean

Booleans have only four valid values – true, false, undefined and null

Array Types

Array types define both that an variable is an array and the kind elements it contains

Enum

Collection of unique strings

Any

  • Can be anything

  • Similar to * in other languages

  • To be avoided

Void

  • Absence of any type

  • Mostly used for function return signatures

Last updated

Was this helpful?