babelcodes
9/16/2017 - 4:50 PM

TypeScript > Basic Types

TypeScript > Type ▶︎ http://babel.codes/TypeScript/Type

// boolean
let isDone :boolean = true; // ":boolean" is optional
 
// Number
let decimal :number = 6; // ":number" is optional
let hex :number = 0xf00d;
let binary: number = 0b1010;
let octal: number = 0o744;
 
// String
let color: string = "blue"; // Double quotes
let otherColor = 'red'; // Simple quotes
let sentence: string = 'Hello, my color is ${ color }.';
 
// Tuple (= array with known size and types can be dirrents)
let x: [string, number];
x = ["hello", 10];
x = [10, "hello"]; // Error
console.log(x[0].substr(1));
console.log(x[1].substr(1)); // Error
// When accessing an element outside, a union type is used instead:
x[3] = "world"; // is 'string | number'
console.log(x[5].toString()); // string and number has toString
x[6] = true; // Error, 'boolean' isn't 'string | number'
 
// Enum
enum Color {Red = 1, Green = 2, Blue = 4}
let c: Color = Color.Green;
let colorName: string = Color[2];
 
// Any (vs Object)
let notSure: any = 4;
notSure = "maybe a string instead";
notSure = false; // okay, definitely a boolean
 
// Void
function warnUser(): void { alert("This is my warning message"); }
let unusable: void = undefined;
 
// Undefined and null
let u: undefined = undefined;
let n: null = null;
// By default null and undefined are subtypes of all other types.
// But can use the --strictNullChecks flag => void
 
// Never (represents the type of values that never occur)
function error(message: string): never { throw new Error(message); }
function fail() { return error("Something failed"); } // Inferred
function infiniteLoop(): never { while (true) { } }
// is a subtype of, and assignable to, every type
 
// Type assertions (cast)
let someValue: any = "this is a string";
let strLength1: number = (<string>someValue).length; // "angle-bracket" syntax
let strLength2: number = (someValue as string).length; // as-syntax