TypeScript学习笔记-变量声明

变量声明

var

let

拥有块级作用域的变量的另一个特点是,它们不能在被声明之前读或写。 虽然这些变量始终“存在”于它们的作用域里,但在直到声明它的代码之前的区域都属于 暂时性死区。 它只是用来说明我们不能在 let语句之前访问它们。

const

它们与let声明相似,但是就像它的名字所表达的,它们被赋值后不能再改变。 换句话说,它们拥有与 let相同的作用域规则,但是不能对它们重新赋值。

这很好理解,它们引用的值是不可变的。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
const numLivesForCat = 9; //猫有九命,O(∩_∩)O哈哈~
const kitty = {
name: 'Garfield',
numLives: numLivesForCat,
}

// Error
kitty = {
name: 'Tom',
numLives: numLivesForCat,
}

// ok
kitty.name = 'Hello';
kitty.name = 'World';
kitty.name = 'Cat';
kitty.numLvies--;

解构

解构数组

1
2
3
let input = [1, 2];
let [first, second] = input;
[first, second] = [second, first];

对象解构

函数声明

1
2
3
4
type C = { a: string, b?: number};
function f({ a, b}: C):void {
// ...
}

展开

1
2
3
4
5
6
7
8
9
let defaults = {
food: 'spicy',
price: '$$',
ambiance: 'noisy'
};
let search = {...defaults, food: 'rich'};
// { food: 'rich', price: '$$', ambiance: 'noisy' }

}