Typescript Step by Step
  • Introduction
  • Types
  • Interface
  • Class
  • Module
  • Function
  • What Next?
Powered by GitBook
On this page
  • Basic Type Example
  • Number
  • String
  • Boolean
  • Array Types
  • Enum
  • Any
  • Void

Was this helpful?

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

var g : number;
g = 6;
g = 1.5;
g = 2 * 6;
g = 10e6;
g = Math.random();
g = "hello"; // compile-time error

String

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

var s : string;
s = "hello world";
s = "o" + "kay";
s = "fundamentals".slice(0,3);
s = 66; // compile-time error

Boolean

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

var b : boolean;
b = true;
b = false;
b = undefined;
b = null;
b = 0; // compile-time error
b = "a"; // compile-time error
b = NaN; // compile-time error

Array Types

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

var numbers : number[] = [];
numbers[0] = 1;
numbers.push("two"); // compile-time error

var strings : string[] = [];
strings.push("hello");
strings[1] = 1337; // compile time error

var things : any[] = [];
things.push(1);
things.push("hello");

Enum

giving more friendly names to sets of numeric values

var colors: string[] = ['red', 'green', 'blue']; // colors[1] => green

// index 0 based (default)
enum colors {red, green, blue};
console.log(colors.green) // 1

// change index
enum colors { red=1, green=3, 'blue' };
console.log(colors.green); // 3

// get enum name using index
enum colors { red=1, green=3, 'blue' };
console.log(colors[3]); // green

Any

  • Can be anything

  • Similar to * in other languages

  • To be avoided

// Ex 1
var w : any;
w = "string";
w = 8;
w = false;
w = [];

// Ex 2
var list:any[] = [1, true, "free"];

Void

  • Absence of any type

  • Mostly used for function return signatures

function warnUser(): void {
    alert("This is my warning message");
}
PreviousIntroductionNextInterface

Last updated 4 years ago

Was this helpful?