这是我参与2022首次更文挑战的第18天,活动详情查看:2022首次更文挑战
祝大家新春快乐
类型断言
介绍
有时候你会比TS更加明确一个变量的类型, 这个时候,可以使用类型断言来制定更具体的类型
使用场景
- 如果我们在
HTML中写了a标签,想要在js中获取DOM结构,那么就可以使用类型断言了 示例
const aLink = document.getElementById("a")
aLink.href = ''
这个时候就会报错因为TS通过类型推到,会标签自动添加一个HTMLElement类型
添加类型断言
const aLink = document.getElementById("a") as HTMLAnchorElement
aLink.href = ''
我们通过 as关键字可以给值添加指定类型断言,当然,除了这种写法,还有另外一种写法
const aLink = <HTMLAnchorElement>document.getElementById("a")
aLink.href = ''
通过尖括号的形式添加
注意
通过尖括号的形式添加类型断言,我们不建议使用,在使用React开发过程中,尖括号的类型断言会和jsx产生冲突
枚举
介绍
定义一组命名常量,他描述一个值,这个值可以是这些命名常量中的任意一个
使用说明
- 使用
enum关键字定义枚举 - 约定枚举名称、枚举中的值以大写字母开头
- 枚举中的多个值之间通过逗号隔开
- 定义好枚举后,直接使用枚举名称作为类型注解 示例
enum Direction {
Top,
Right,
Bottom,
Left
}
function changeDirection(direction:Direction) {
console.log(direction);
}
changeDirection(Direction.Top) // 0
changeDirection(Direction.Right) // 1
changeDirection(Direction.Bottom) // 2
changeDirection(Direction.Left) // 3
注意点
- 上边的代码,我们可以看到,把枚举成员作为函数的实参,他的值默认是从0开始自增的,我们称为
数字枚举 - 同时我们也可以初始化成员中的值
enum Direction {
Top = 10,
Right,
Bottom,
Left
}
function changeDirection(direction:Direction) {
console.log(direction);
}
changeDirection(Direction.Top) // 10
changeDirection(Direction.Right) // 11
changeDirection(Direction.Bottom) // 12
changeDirection(Direction.Left) // 13
这个时候我们把枚举中Top的值设为10,从设置值后边的枚举值也是自增的
字符串枚举
示例
enum Direction {
Top = "Top",
Right = "Right",
Bottom = "Bottom",
Left = "Left"
}
function changeDirection(direction: Direction) {
console.log(direction);
}
changeDirection(Direction.Top) // Top
changeDirection(Direction.Right) // Right
changeDirection(Direction.Bottom) // Bottom
changeDirection(Direction.Left) // Left
枚举除了设置数字枚举,我们还可以设置字符串枚举
- 注意
字符串枚举没有自增长行为,所以如果给枚举中的某个值设为字符串类型,那么所有的枚举值都必须给定对应的字符串值,否则提示会报错
写在最后
- 希望你能收获满满