Typescript 常用變量類型聲明

函數聲明變量

// 基礎類型(number、boolean、string)
const int = (arg1: number) {
	// ...
}
// 數組類型
const arr1 = (arg1: number[]) {
	// ...
}
// 另一種寫法,使用泛型
const arr2 = (arg1: Array<number>) {
	// ...
}
// 任意類型(any)
// any: 表示參數可以爲任意類型
const any = (arg1: any) {
	// ...
}

對象聲明 (接口: interface)

interface LabelType {
	id: number;  // label id
	txt: string; // label值
}

const func1 = (obj: LabelType) {
	// ...
}
// 或者使用解構的寫法
const func2 = ({ id, txt }: LabelType) {
	// ...
}
func({
	readonly id: 1, // 'readonly' 表示只讀屬性
	txt?: 'this is a string.' // '?' 表示爲可選屬性
})

類型斷言

let str: any = "this is a string."
// 第一種使用尖括號的用法
let asset1: number = (<string>str).length
// 另一種使用 as 語法
let asset2: number = (str as string).length

泛型

// 聲明泛型函數
function identify<T>(arg: T): T {
	// ...
}
// 使用泛型約束
const str1 = identify<string>("this is a string.");
// 另一種簡潔寫法
const str2 = identify("this is other string.")
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章