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
注意: 类型断言属于强制性转换,所以会丧失ts代码提示的能力 双重断言,但是更不建议使用,少见的场景下也有用武之地
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);
posted @ 2022-02-17 14:42  ~柚子~  阅读(332)  评论(0)    收藏  举报