15类型断言
# 类型断言
- 类型断言可以用来手动指定一个值的类型。
==语法==
值 as 类型(推荐)
//或
<类型>值
1
2
3
2
3
# 1、将一个联合类型断言为其中一种
//val的联合类型为number和string,而number类型并没有length属性,所以直接使用会报错
function fn(val:number|string){
console.log(val.length)
}
fn("hello")
//这时候将val断言为string就可以解决
function fn(val:number|string){
console.log((val as string).length)
}
fn("hello")
1
2
3
4
5
6
7
8
9
10
11
12
13
2
3
4
5
6
7
8
9
10
11
12
13
注意,断言只能欺骗ts编译器,并不能避免运行时的错误
//断言并不能把number类型的123转为string的123,所以下列代码在运行的时候是错的
function fn(val:number|string){
console.log((val as string).length)
}
fn(123)
1
2
3
4
5
6
2
3
4
5
6
//练习
function fn(arg: string | number) {
console.log((arg as string).length);
}
fn("hello")//hello
fn(1);//undefined //因为数字1没有length了
1
2
3
4
5
6
2
3
4
5
6
# 2、将一个父类断言为更加具体的子类
//由于Person没有study属性,故直接通过p.study调用会报错
class Person{}
class Student extends Person{
study:string = "学习"
}
class Teacher extends Person{
work:string = "工作"
}
function fn(p:Person){
console.log((p as Student).study)
}
fn("小明")
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
# 3、将任何一个类型断言为any
//如果直接给window赋值aaa是错误的,因为window上没有aaa这个属性
window.aaa = 1
//解决办法是把window断言为any类型
(window as any).aaa = 1
1
2
3
4
5
2
3
4
5
# 4、将any断言为一个具体的类型
//可精确的提高代码的具体类型,以提高代码维护性
function fn():any{
return "hello"
}
let str = fn() as string
console.log(str)
1
2
3
4
5
6
7
2
3
4
5
6
7
# 5、类型守卫
- 可通过
instanceof、in等进行类型守卫。
1、instanceof一般用于判断类
class Teacher{
work(){
console.log("工作")
}
}
class Student{
study(){
console.log("学习")
}
}
function fn(arg:Teacher|Student){
if(arg instanceof Teacher){//类型守卫
arg.work()
}else{
arg.study()
}
}
fn(new Teacher())
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
2、in判断类或者对象里面是否有某个属性
interface p1{
name:string
}
interface p2{
age:number
}
function fn(arg:p1 | p2){
if("name" in arg){
console.log("p1")
}else{
console.log("p2")
}
}
fn({name:"小明"})//p1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
编辑 (opens new window)
上次更新: 2023/08/06, 00:38:41