-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathvariables.ts
68 lines (45 loc) · 1.2 KB
/
variables.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
let apples: number = 5
let speed: string = "10km"
let hashName: boolean = true;
let nothingMuch: null = null
let nothing: undefined = undefined
// built in objects
let now: Date = new Date()
// Array
let colors: string[] = ['red', 'green', 'blue']
let myNumbers: number[] = [1,2,3]
let truths: boolean[] = [true,true,false]
// Class
class Car {
}
let car: Car = new Car()
// Object Literal
let point: {x: number, y:number} = {
x: 10,
y:20
}
// Function
const logNumber: (i: number) => void = (i: number) => {
console.log(i)
}
// When to use annotations
// 1) function that returns the 'any' type
const json = '{"x": 10, "y": 20}';
const coordinates: {x:number, y:number} = JSON.parse(json)
console.log(coordinates)
// 2) When we declared a variable on one line and initalizate it later
const words = ["red", "green", "blue"]
let foundWord: boolean
for (let i = 0; i < words.length; i++) {
if(words[i] === "green") {
foundWord = true
}
}
// 3) Variable whose type cannot be inferred correctly
let numbers = [-10, -1, 12]
let numberAboveZero: boolean | number = false;
for (let i = 0; i < numbers.length; i++) {
if(numbers[i] > 0) {
numberAboveZero = numbers[i]
}
}