typescript重学-基础类型
2023-02-09 本文已影响0人
羽晞yose
该系列基于typescript中文文档官网重新学习编写的demo,部分描述未必正确,又或者说对到typescript
中不一定正确,仅做学习记录,该系列源于ts4.9.5版本进行试验,与官网相比是不会一直重复串知识点,方便聚焦知识点的实现
string类型
let stringType: string = '字符串'
let sentence: string = `这是一个类型为${stringType}的句子`
// stringType = 123 // ts报错,类型一经指定不允许变更
console.log(stringType, sentence)
布尔类型
let booleanType: boolean = true
console.log(booleanType)
数值类型,二进制、八进制、十进制、十六进制均合法可识别
let decLiteral: number = 6 // 十进制
let hexLiteral: number = 0xf00d // 十六进制,以0x开头
let binaryLiteral: number = 0b1010 // 二进制,以0b开头
let octalLiteral: number = 0o744 // 八进制,以0开头
console.log(decLiteral, hexLiteral, binaryLiteral, octalLiteral)
数组类型
let arrayType: Array<number> = [1, 2, 3]
let arrayType2: string[] = ['1', "2", `3`]
console.log(arrayType, arrayType2)
元组类型,允许表示一个已知元素数量和类型的数组,各元素的类型不必相同
let tupleType: [string, number] = ['string', 2]
console.log(tupleType)
// console.log(tupleType[2]) // 报错,访问了一个超过其长度限制的索引
// tupleType[2] = "abc" // 报错,不能将类型"abc"分配给类型“undefined”,但是文档可以,应该是中文文档没对应最新版ts
枚举类型,左边是值,右边是元素编号
如果值是数值(也就是下标,是允许通过下标取key的,否则只能通过key取value)
enum Color { red, green, blue }
const redColorIndex = Color['red'] // 0
const greenColor = Color[1] // 'green'
console.log(redColorIndex, greenColor)
如果值非数值,则只能通过键来取值,不允许反取(Color['r']
),否则即使写成Color['r' as keyof typeof Color]
,解决掉报错构建出来的结果也不对,依然会获取到undefined
enum Color {
red = 'r' ,
green = 'g',
blue = 'b'
}
let getColor: string = Color['red']
console.log(getColor)
any类型,允许发生变更,用于变量的指定类型,不同于Object类型,其方法也是允许使用的
let anyType: any = ['test', 123, [0]]
anyType[2] = 123 // 变更类型,超过边界都是可以的
anyType = 'change'
let anyObjectType: Object = "abc"
anyObjectType = 4.125
// anyObjectType.toFixed(3) // 虽然允许改变类型,但是使用方法的时候会报错
console.log(anyType, anyObjectType)
void类型,表示无任何返回
// let unusable: void = null // 旧版ts中null也会合法,需要开启了strictNullChecks,新版中默认为开启,如果需要关闭需要设置为false
function voidFn(): void {
console.log('函数不返回任何内容')
return undefined // 这个是合法的,但不能返回null或其他基本类型
}
voidFn()
null 和 undefined类型,旧版里为其他类型子集,新版中默认已开启strictNullChecks,所以不合法
// let nullType: number = undefined
let nullType: null = null
let undefinedType: undefined = undefined
let mutipleType: number | null | undefined = 123
console.log(nullType, undefinedType, mutipleType)
never类型,表示永远不会执行到,可以赋值给任何类型,但任何其他类型均不能赋值给never
function errorFn(message: string): (never | Error) { // 这么写是为了让下面不会被检测为不会被执行的代码
throw Error(message)
}
errorFn('报错啦')
function fail(message: string): Error {
return Error(message)
}
fail('失败')
// 这个不要跑run code
function infiniteLoop(): never {
while (true) {
}
}
infiniteLoop()
object类型
该类型实际开发中基本用不到,表示非原始类型,作为约束不够严谨,作为类型又无法使用对象方法,仅做记录
declare function create(o: object | null): void;
create({ prop: 0 })
create(null)
类型断言
尖括号语法
let someValue: any = "this is a string"
let strLength: number = (<string>someValue).length
as
语法,JSX中只能使用该语法
let replaceStr: string[] = (someValue as string).split(' ')
console.log(strLength, replaceStr) // 16, [ 'this', 'is', 'a', 'string' ]