/**
* 类型断言,可以用来手动指定一个值的类型
* 语法:
* 值 as 类型 或 <类型>值
*
* 用途:
* 1、将一个联合类型断言为其中一个类型
* 2、将一个父类断言为更加具体的子类
* 3、将任何一个类型断言为any
* 4、将any断言为一个具体的类型
* 要使得 A 能够被断言为 B,只需要 A 兼容 B 或 B 兼容 A 即可
*
* 类型断言不是类型转换,不会影响变量的类型
*/
// 第一种
interface Cat {
name: string;
run(): void;
}
interface Fish {
name: string;
swim(): void;
}
// function isFish(animal: Cat | Fish) {
// if(typeof animal.swim === 'function') { //此时swim会报错,因为cat接口没有swim方法
// return true;
// }
// return false;
// }
function isFish(animal: Cat | Fish) {
if(typeof (animal as Fish).swim === 'function') { //但是这样会隐藏animal可能为Cat的情况,将animal直接断言为Fish
return true;
}
return false;
}
// 第二种
class ApiError extends Error {
code:number = 0;
}
class HttpError extends Error {
statusCode:number = 200;
}
function isApiError(error: Error) {
if(typeof (error as ApiError).code === 'number'){
return true;
}
return false;
}
// 第三种
const foo: number = 1;
// foo.length = 1; //当引用一次词类型上不存在的属性和方法时会报错
// window.foo = 1; //但这种情况ts编译也会报错,window上没有foo属性,此时可以使用断言
(window as any).foo = 1;
// 第四种
function getCacheData(key: string): any {
return (window as any).cache[key];
}
interface Cat {
name: string;
run(): void;
}
const toms = getCacheData('tom') as Cat;
tom.run();
ts类型断言-as
最新推荐文章于 2024-08-01 11:08:20 发布