基础类型
boolean 类型
const isStatus: boolean = true
console.log(isStatus)
![](https://img.haomeiwen.com/i6286160/a71c87cc64d686b3.png)
注意:赋值与定义的不一致,会报错;
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)
![](https://img.haomeiwen.com/i6286160/8c077320d3c71f8c.png)
any 类型
_ 不清楚用什么类型,可以使用 any 类型。这些值可能来自于动态的内容,比如来自用户输入或第三方代码库_
let notSure: any = 4
notSure = "maybe a string" // 可以是 string 类型
notSure = false // 也可以是 boolean 类型
notSure.name // 可以随便调用属性和方法
notSure.getName()
不建议使用 any,不然就丧失了 TS 的意义。
数组类型
const list: number[] = [1, 2, 3]
list.push(4)
_ 数组里的项写错类型会报错_
const list2: number[] = [1, 2, "3"]
![](https://img.haomeiwen.com/i6286160/0d6cf7bbc2e0bc54.png)
_ push 时类型对不上会报错_
list2.push("123")
![](https://img.haomeiwen.com/i6286160/2ffabc103f7d99a3.png)
如果数组想每一项放入不同数据怎么办?用元组类型
元组类型
_ 元组类型允许表示一个已知元素数量和类型的数组,各元素的类型不必相同_
const tuple: [number, string] = [18, "lin"]
console.log(tuple)
// 数组里的项写错类型会报错
const tuple2: [number, string] = ["lili", 20]
console.log(tuple2)
![](https://img.haomeiwen.com/i6286160/7400808639b7bd3e.png)
// 越界会报错:
const tuple3: [number, string] = [18, "lin", true]
![](https://img.haomeiwen.com/i6286160/8a09dda19686eda1.png)
- 可以对元组使用数组的方法,比如使用 push 时,不会有越界报错_
const tuple4: [number, string] = [18, "lin"]
tuple4.push(100)
push 一个没有定义的类型,报错
const tuple4: [number, string] = [18, "lin"]
tuple4.push(true)
![](https://img.haomeiwen.com/i6286160/87f9e3b85de7612e.png)
网友评论