ts类型断言和类型守卫
1、类型断言
情况:有些时候ts会根据类型推断报错,在万不得已的情况下使用断言推断要谨慎
点击查看代码
//类型断言
interface privateInfo{
name:string,
id: number
}
const params = {} as privateInfo
params.name = 'd';
//双重断言
interface Person {
name: string;
age: number;
}
const person = 'xiaomuzhu' as any as Person; // ok
2、类型守卫
(1)instanceof用于检测前面的对象是否与后面的对象匹配
点击查看代码
class Animals{
color = 'white'
sound = 'wang'
}
class Cars {
speed = 500
run = true
}
function typeTest(params: Animals | Cars) {
//如果当前这个对象属于Animals,则ts可以检测到color和sound属性
if (params instanceof Animals) {
console.log(params.color); //white
// console.log(params.speed); //error
}
//如果当前这个对象属于Cars,则ts可以检测到speed和run属性
if (params instanceof Cars) {
console.log(params.speed);
// console.log(params.color); //error
}
}
const animals = new Animals();
typeTest(animals);
(2)in表示前面的属性是否在后面的对象内
点击查看代码
class Dogs {
run = true
sound = true
}
class Pencils {
color = 'black'
length = 10
}
function inTest(arg: Dogs | Pencils) {
if ('sound' in arg) {
console.log(arg.sound);
// console.log(arg.color); //error
}
if ('color' in arg) {
console.log(arg.color); //black
// console.log(arg.sound); //error
}
}
const pencil = new Pencils();
inTest(pencil);
注意:此时在做in的检测时,后面的对象应该是参数本身,而不是class对象
3、字面量类型守卫
点击查看代码
//type是用来申明一个类型的,最终都会赋值给某个变量
type Foo = {
name: 'mao',
score1: number
}
type Bar ={
name: 'ding',
score2: number
}
function testScore(arg:Foo|Bar) {
//字面量是否相等判断:==, ===, !=, !==
if (arg.name === 'mao'){
console.log(arg.score1);
// console.log(arg.score2); //error
} else {
// console.log(arg.score1); //error
console.log(arg.score2); //20
}
}
const bar:Bar = {
name: 'ding',
score2: 20,
}
testScore(bar);
浙公网安备 33010602011771号