基礎(chǔ)類型
boolean 類型
const isStatus: boolean = true
console.log(isStatus)
image.png
注意:賦值與定義的不一致土陪,會(huì)報(bào)錯(cuò);
number 類型
const num: number = 123
console.log(num)
string 類型
const realName1: string = "lin"
const fullName: string = `A ${realName1}` // 支持模板字符串
console.log(realName1)
console.log(fullName)
undefined 和 null 類型
const u: undefined = undefined // undefined 類型
const n: null = null // null 類型
console.log(u)
console.log(n)
const age: number = null
const realName: string = undefined
console.log(age)
console.log(realName)
image.png
any 類型
_ 不清楚用什么類型,可以使用 any 類型伏嗜。這些值可能來自于動(dòng)態(tài)的內(nèi)容,比如來自用戶輸入或第三方代碼庫(kù)_
let notSure: any = 4
notSure = "maybe a string" // 可以是 string 類型
notSure = false // 也可以是 boolean 類型
notSure.name // 可以隨便調(diào)用屬性和方法
notSure.getName()
不建議使用 any宴卖,不然就喪失了 TS 的意義纺阔。
數(shù)組類型
const list: number[] = [1, 2, 3]
list.push(4)
_ 數(shù)組里的項(xiàng)寫錯(cuò)類型會(huì)報(bào)錯(cuò)_
const list2: number[] = [1, 2, "3"]
image.png
_ push 時(shí)類型對(duì)不上會(huì)報(bào)錯(cuò)_
list2.push("123")
image.png
如果數(shù)組想每一項(xiàng)放入不同數(shù)據(jù)怎么辦?用元組類型
元組類型
_ 元組類型允許表示一個(gè)已知元素?cái)?shù)量和類型的數(shù)組悼瓮,各元素的類型不必相同_
const tuple: [number, string] = [18, "lin"]
console.log(tuple)
// 數(shù)組里的項(xiàng)寫錯(cuò)類型會(huì)報(bào)錯(cuò)
const tuple2: [number, string] = ["lili", 20]
console.log(tuple2)
image.png
// 越界會(huì)報(bào)錯(cuò):
const tuple3: [number, string] = [18, "lin", true]
image.png
- 可以對(duì)元組使用數(shù)組的方法戈毒,比如使用 push 時(shí),不會(huì)有越界報(bào)錯(cuò)_
const tuple4: [number, string] = [18, "lin"]
tuple4.push(100)
push 一個(gè)沒有定義的類型横堡,報(bào)錯(cuò)
const tuple4: [number, string] = [18, "lin"]
tuple4.push(true)
image.png