TypeScript - 使用筆記 (1)
TypeScript宣告類型的方式
Explicit : 不需要加上類型宣告,會自動偵測推斷型別 (Type Inference)
const color = "Yellow"
Implicit:可以手動加上類型宣告 (Type Assertions)
const color:string = "Yellow"
- 省略
:型別
時 - 一但宣告後,會自動偵測型別並鎖定,不能被重新賦值成其他型別
let str = 'hello'str = 77 // error: Type 'number' is not assignable to type 'string'let names = ['John','Paul','Ringo','Geroge']names[0] = 3 // error: Type 'number' is not assignable to type 'string'
原始型別
1. Boolean
const x :boolean = trueconst y :boolean = false
2. Number
//十進位const a : number = 100;
3. String
- 可以使用「`」符號將字串括起來
- 可保留空換行
const x : string = "abc" ;const y : string = 'def' ;const z : string = ` Hello world! Hello world! `
4. Null 和 Undefined
let u: undefined = undefined;let n: null = null;
5. unkonwn
- 表示未知類型的值
- 可看作是類型安全的any
- 不能直接賦值給其他變數
let a:unkonwna = 1 //oka = true // oka = 'hi' //oklet e:stringe = a // error// okif(typeof e === 'string'){ e = a }
6. never
- 永遠不會有回傳結果
- 或總是拋出錯誤的函
function fn():never { throw new Error('錯誤')}
7. any
- 任意類型
// 兼容所有類型,建議少用 (像在寫JS)let test: any = true
Union Types
- 聯合型別
- 可以有複數的型別
let mixed: (string|number)[] = []mixed.push('hello type')mixed.push(24)let money: string|numbermoney = '999'money = 999let answer: string | boolean// gender的值只能是以下2者let gender: 'male' | 'female' gender = 'happy' // error
型別斷言
- 當不確定一個聯合類型的變數到底是哪個類型時,只能訪問此聯合類型中的所有類型共有的屬性或方法
- 有時候希望在不確定類型的時候就訪問其中一個類型特有的屬性或方法
語法
1. 值 as 類型 2. <類型>值
let str: any = 'hello';let str2 = str as string;let str3 = <string>str;
//example1let myVar: unknown = "Hello world!";console.log((myVar as string).length);//example2let myVar: unknown = "Hello world!";console.log((<string>myVar).length);
將一個聯合類型推斷為其中一個類型
- 使用型別斷言,將
something
斷言成string
function getLength(something: string | number): number { if ((<string>something).length) { return (<string>something).length; } else { return something.toString().length; }}
- 型別斷言不是型別轉換,斷言成一個聯合型別中不存在的型別是不允許的
function toBoolean(something: string | number): boolean { return <boolean>something;}// index.ts(2,10): error TS2352: Type 'string | number' cannot be converted to type 'boolean'.// Type 'number' is not comparable to type 'boolean'.
DOM
// 當確定回傳的值不會是null,可以加上!取消警告const anchor = document.querySelector('a')!console.log(anchor.href)
// type: HTML element// 使用HTML標籤抓取,ts可以判斷是什麼類型const form1 = document.querySelector('form')!// type: element// 使用class抓取,無法判斷這是什麼類型// 可用 as 指定會是什麼類型const form = document.querySelector('.new-item-form') as HTMLFormElementconst input1 = document.querySelector('.num1')! as HTMLInputElement
參考資料
# TypeScript