“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
Collection of unique strings
enum OrderStatus {complete,pending,declined};
var n : OrderStatus;
n = OrderStatus.complete;
n = OrderStatus.unfinished; // compile-time error
n = "on the way"; // compile-time error
Any
Can be anything
Similar to * in other languages
To be avoided
var w : any;
w = "string";
w = 8;
w = false;
w = [];
Void
Absence of any type
Mostly used for function return signatures
function nothing () : void {
var g = "I don't return anything.";
}