文章列表

类型守卫函数

Champ2025.12.18 16:13访问量0 次阅读
类型守卫函数
TS中的类型守卫函数学习

什么是类型守卫函数?

类型守卫函数是 TypeScript 中一种特殊的函数,它用于在运行时检查变量的类型,并告诉 TypeScript 编译器在特定的代码块中,该变量具有什么类型。

基本语法

function isType(value: any): value is SpecificType {
  // 返回布尔值
  // 如果返回 true,TypeScript 会认为 value 是 SpecificType 类型
}

为什么需要类型守卫?

//不使用类型守卫的情况,ts不知道它是什么类型
interface User {
  id: number;
  name: string;
  email: string;
}

interface Error{
    id:number;
    message:string;
    code:number;
}

// 普通函数 - 只是返回 boolean
//TypeScript 不知道当它为 true 时,data 就是 User 类型
//也不知道当它为 false 时,data 就是 Error 类型
function isValidUser(obj: any): boolean {
  return (
    typeof obj === 'object' &&
    typeof obj.id === 'number' &&
    typeof obj.name === 'string' &&
    typeof obj.email === 'string' &&
    obj.email.includes('@')
  );
}

function getData(){
    const user:User = {
    id: 3,
    name: 'champ',
    email: '2581113213@qq.com'
};

    const error:Error ={
    id: 4,
    message: 'dataerror',
    code: 200,
}

    const ran = Math.round(Math.random());
    console.log(ran);
    if(ran%2) return error;
    return user;
}

// 使用时...
const data:unknown= getData();

if (isValidUser(data)) {
  // ❌ TypeScript 不知道 data 是 User 类型!
  // data 仍然是 unknown 或 any
   console.log(data.name);  // 错误:类型"unknown"上不存在属性"name"
   console.log(data.email); // 错误:类型"unknown"上不存在属性"email"

  //需要手动断言
  const userData = data as User;
  console.log(userData.name);
  console.log(userData.email);
}
else{
    const errordata = data as Error;
    console.log(errordata.message);
}
//使用类型守卫的情况
interface User {
  id: number;
  name: string;
  email: string;
}

interface Error{
    id:number;
    message:string;
    code:number;
}

function isValidUser(obj: any): obj is User {
  return (
    typeof obj === 'object' &&
    typeof obj.id === 'number' &&
    typeof obj.name === 'string' &&
    typeof obj.email === 'string' &&
    obj.email.includes('@')
  );
}

function getData(){
    const user:User = {
    id: 3,
    name: 'champ',
    email: '2581113213@qq.com'
};

    const error:Error ={
    id: 4,
    message: 'dataerror',
    code: 200,
}

    const ran = Math.round(Math.random());
    console.log(ran);
    if(ran%2) return error;
    return user;
}

// 使用时...
const data:User | Error= getData();

if (isValidUser(data)) {
  // ✅ 
  //类型守卫告诉ts,如果返回真,obj就是User类型
  //此时 data 已经是User类型
  console.log(data.name);
  console.log(data.email);

  //不需要手动断言
//   const userData = data as User;
//   console.log(userData.name);
//   console.log(userData.email);
}
else{
    //else,则是另一种类型Error,无需手动断言
    // const errordata = data as Error;
    console.log(data.message);
}
历史留言 (0)
ICP备案号浙ICP备2026065730号-1公安备案号浙公网安备33019202003213号