# TypeScript 基礎知識
###### tags: `TypeScript`
---
~~*ps.作為自己學習筆記之用,如有錯漏請高抬貴手QQ*~~
## 一般變數宣告
TypeScript的變數皆於一開始就宣告變數型別,可避免JavaScript變數型別轉換可能的錯誤,對於之後程式維護與Debug可說是非常有幫助。
* 有幾種變數宣告型別
* <span class="code1">var</span>
* <span class="code1">let</span>
* <span class="code1">const</span>
* <span class="code2">Tuple</span>
變數的宣告方式:
```typescript=
var abc:string = "Hello"; //宣告為字串
var num:number = 12; //宣告為數字
var apple:any = 10; //可存放任意型別的值
let bca:string;
const sum = 50; //設定常數型別
let ayy:number[]= [1,2,3,4,5];
```
也可以自訂變數名稱,並設定對應的型別:(好處是之後查找型別非常方便)
```typescript=
type phone = number; //使用let a:phone; 取用變數
type email = string; //使用let b:email; 取用變數
type ayy = string[];
```
---
## 列舉型別(enum)
特色為只能預先存入固定數量的內容值的型別,建立後無法再存入其他的值。
```typescript=
enum Season { spring, summer, autumn, winter };
let s: Season = Season.summer; //取用enum Season的值
switch (s) {
case Season.spring:
document.write('<h1>Spring</h1>');
break;
case Season.summer:
document.write('<h1>Summer</h1>');
break;
case Season.autumn:
document.write('<h1>Autumn</h1>');
break;
case Season.winter:
document.write('<h1>Winter</h1>');
break;
}
document.write('<p>顯示目前的季節:</p>');
```
---
## Tuple 型別變數
```typescript=
type name = string;
type phone = number;
type email = string;
let person[name, phone, email];
person['Peter', 0900123456, 'abc@g.com'];
person['Ella', 0900123466, 'abc@g.com'];
document.write(person);
```
---
<span class="code1"></span>
<style>
h2 {
color: #2383B8;
}
h3 {
color: #1AA340;
}
h4 {
color: white;
background-color: #2383B8;
padding:8px;
}
.code1 {
padding: 2px 4px;
font-size: 90%;
color: #c7254e;
background-color: #f9f2f4;
border-radius: 4px;
font-family:'Fira Code';
}
.code {
padding: 2px 4px;
font-size: 90%;
font-family:'Fira Code';
}
</style>