Skip to content

Typescript

Thomas Czogalik edited this page Sep 1, 2020 · 5 revisions

Type Inference

let x = 3;
  • variable is inferred to be number

Best common type

let x = [0, 1, null];
  • choices for the type of the array: number and null
  • best common type has to be chosen from the provided candidate types
  • because there is no object that is strictly of type Animal in the array, we make no inference about the array element type
  • explicitly provide the type
let zoo: Animal[] = [new Rhino(), new Elephant(), new Snake()];
  • When no best common type is found, the resulting inference is the union array type, (Rhino | Elephant | Snake)[]

Get/Set

  • getter and setter using get and set keyword
  • method name needs to be the same as the property
interface Props {
    firstDay: Date
}

get firstDay(): Date {
    return this.firstDay;
};

set firstDay(date: Date) {
    this.firstDay = date;
}

Foreach won't break (also JavaScript)

you can’t break forEach.

var arr = ["Kathmandu", "Pokhara", "Lumbini", "Gorkha"];
 
arr.forEach(function(value, index, _arr) {
    console.log(index + ": " + value);
    return false;
});

output:
0: Kathmandu
1: Pokhara
2: Lumbini
3: Gorkha

some

the same as forEach but it break when the callback returns true.

var arr= ["Kathmandu", "Pokhara", "Lumbini", "Gorkha"];
 
arr.some(function (value, index, _arr) {
    console.log(index + ": " + value);
    return value === "Pokhara";
});

output:	
0: Kathmandu
1: Pokhara

each

it’s expecting false to break the loop

 
arr.every(function(value, index, _arr) {
    console.log(index + ": " + value);
    return value.indexOf("Lumbini") < 0;
});

output:	
0: Kathmandu
1: Pokhara
2: Lumbini

Clone this wiki locally