2022-11-30 21:50

TypeScript入门(4) — 类型断言和类型守卫

王姐姐

WEB前端

(417)

(0)

收藏

1. 类型断言

类型断言好比其他语言里的类型转换,但是不进行特殊的数据检查和解构。它没有运行时的影响,只是在编译阶段起作用。

1.1. “尖括号” 语法

let anyVal: any = "hello";
let len: number = (<string>anyVal).length;
console.log(len);

1.2. as 语法

let anyVal: any = "hello";
//let len: number = anyVal.length;
//let len: number = (<string>anyVal).length;
let len: number = (anyVal as string).length;
console.log(len);

其中anyVal.length不出错也能获得字符串长度,但是编写代码时没有提示。

2. 类型守卫

类型保护就是一些表达式,它们会在运行时检查以确保该类型在一定的范围内。

2.1. in 关键字

interface Admin{
    name: String;
    age: number;
}
interface Userinfo{
    name: string;
    sex: String;
}   
type User = Admin|Userinfo;
function showInfo(user: User){
    console.log(user.name);
    if("age" in user){
        console.log(user.age);        
    }
    if("sex" in user){
        console.log(user.sex);
    }    
}

如果Student类没有实现Admin接口或者Userinfo接口,则Student对象不能作为showInfo的参数:

let  stu = new Student("ma","wan");

//类型“Student”的参数不能赋给类型“User”的参数

showInfo(stu);

如果Student实现了Admin接口或者Userinfo接口,则showInfo(stu)就可以,如果实现了Admin接口,则打印name和age,如果实现了Userinfo接口,则打印name和sex。

class Student implements Admin {
    firstName : string;
    lastName : string;
    name!: String;
    age!: number;
   
    constructor(fiestName : string,  lastName : string) {
        this.firstName = fiestName;
        this.lastName = lastName;
    }
......
}

2.2. typeof 关键字

function printInfo(value: number|string){
    if(typeof value === "number"){
        console.log("number="+value);
    }
    else if(typeof value === "string"){
        console.log("string="+value);
    }
}
printInfo("hello")

打印string=hello。

typeof 类型保护只支持两种形式:typeof value === "typename" 和 typeof value !== typename,"typename" 必须是 "number", "string", "boolean" 或 "symbol"。

2.3. instanceof 关键字

instanceof用于检测实例的类型,右侧要求是一个构造函数。

class Animal{}
class Dog implements Animal{}
let a:Animal = new Dog();
console.log(a instanceof Animal); //false
console.log(a instanceof Dog); //true

2.4. 自定义类型谓词(is 关键字 )

类型谓词(type predicates):为parameterName is Type这种形式。parameterName必须来自于当前函数签名里的一个参数名。

is 关键字一般用于函数返回值类型中,判断参数是否属于某一类型,并根据结果返回对应的布尔类型。
定义一个类型保护,只要简单地定义一个函数,其返回值是一个类型谓词。

class Fish {
    swim () {
        console.log('游泳~');
    }
    eat () {
        console.log('进食!');
    }
}
class Bird {
    fly () {
        console.log('飞翔~');
    }
    eat () {
        console.log('进食!');
    }
}
function getSmallPet(): Fish | Bird {
    return Math.random() > 0.5 ? new Fish() : new Bird()
}
let pet = getSmallPet();//不确定是Fish还是Bird
pet.eat();
function isFish(pet: Fish | Bird): pet is Fish {
    return (pet as Fish).swim !== undefined;
}
if (isFish(pet)) {
    pet.swim();
} else {
    pet.fly();
}


0条评论

点击登录参与评论