一、将任何一个类型断言为any
ts 的类型系统运转良好,每个值类型都具体而精确。当我们引用一个在此类型 上不存在的属性或方法时,就会报错:
const num: number = 1
num.length = 1
// error: Property ' length' does not exist on type ' number '
上面的例子中,数字类型的变量 num 是没有length 属性的,故ts给出了相应的错误提示。
但有的时候,我们非常确定这段代码不会出错,比如下面这个例子:
window.num = 1
// error: Property 'num' does not exist on type 'Window & typeof globalThis'
上面的例子中,我们需要将window.上添加一个属性 num,但ts编译时会报错,提示我们window上不存在nun属性。 此时我们可以使用 as any 临时将 window 断言为 any 类型
(window as any).num = 1;
在any类型的变量上,访问任何属性都是允许的。
注意 :将一个变量断言为any可以说是解决ts中类型问题的最后一个手段。 它极有可能掩盖了真正的类型错误。如果不是非常确定,就不要使用 as any
我们不能滥用 as any ,也不要否定它的作用
二、将any断言为一个具体的类型
在开发中,我们不可避免需要处理any类型的变量,它们可能是由于第三方库未能定义好自己的类型,也有可能是历史遗留的或其他人编写的烂代码,还可能是受到ts类型系统的限制而无法精确定义类型的场景。
遇到any类型的变量时,我们可以选择无视它,任由它滋生更多的any。
我们也可以选择改进它,通过类型断言及时把any断言为精确的类型,亡羊补牢,使我们的代码向着高可维护性的目标发展。
例如项目之前定义了一个 getCalander,它的返回值是any:
const getCalander = (key: string): any => {
return (window as any).cache[key];
}
那么我们在使用它时,最好能够将调用了它之后的返回值断言成一个精确的类型, 这样就方便了后续的操作:
选择语言
const getCalander = (key: string): any =>{
return (window as any). cache[key];
}
interface CalanderType {
date: string;
callCurrentData(): void;
}
const getCurrentDate = CalanderType( '2022-05-03') as CalanderType;
getCurrentDate.run();
上面的例子中,我们调用完getCalander之后,将它断言为CalanderType类型,从而明确getCurrentDate的类型,后续对getCurrentDate的访问时就有了代码补全,提高承俄码以可维护性。
三、类型断言的限制
根据之前的例子,我们可以得出:
1、联合类型可以被断言为其中一个类型
2、父类可以被断言为子类
3、任何类型都可以被断言为any
4、 any 可以被断言为任何类型
那么类型断言有没有什么限制呢?是不是任何一个类型都可以被断言为任何另一个类型呢?
其实并不是任何一个类型都可以被断言为任何另一个类型。
具体来说,若A兼容B,那么A能够被断言为B,B也能被断言为A。
下面我们通过一个简化的例子,来理解类型断言的限制:
interface Animal {
name: string;
}
interface People {
name: string;
run(): void;
}
const Animal1 = (animal: Animal) => {
return (animal as People);
}
const isMySelf = (mySelf: People) => {
return (mySelf as Animal);
}
上例是可以断言的,我们再看看下面的栗子:
interface Animal {
name: string;
}
interface People {
run(): void;
}
const Animal1 = (animal: Animal) => {
return (animal as People);
}
const isMySelf = (mySelf: People) => {
return (mySelf as Animal);
}