类型断言, 类型注解
下面分别介绍将 const meta = matches[matches.length - 1].data as MetaProps;
改为 const meta: MetaProps = matches[matches.length - 1].data;
以及反向更改时会发生的情况,并给出相应的代码示例。
1. 将 const meta = matches[matches.length - 1].data as MetaProps;
改为 const meta: MetaProps = matches[matches.length - 1].data;
代码示例
// 定义 MetaProps 接口
interface MetaProps {
activeMenu: string;
}
// 模拟 matches 数组
const matches = [
{
data: 123 // 这里 data 是 number 类型,不符合 MetaProps 类型
}
];
// 使用类型断言
// const meta = matches[matches.length - 1].data as MetaProps;
// console.log(meta.activeMenu);
// 改为类型注解
const meta: MetaProps = matches[matches.length - 1].data;
console.log(meta.activeMenu);
分析
- 类型断言(原代码):使用
as MetaProps
进行类型断言时,TypeScript 编译器会直接相信你提供的类型,不会对data
的实际类型进行严格检查。即使data
是number
类型,也不会报错,但在运行时可能会因为访问activeMenu
属性而出现错误。 - 类型注解(修改后代码):当改为类型注解时,TypeScript 编译器会严格检查
data
的类型是否符合MetaProps
类型。由于data
是number
类型,与MetaProps
类型不兼容,编译器会抛出错误,阻止代码继续编译。错误信息可能类似于:Type 'number' is not assignable to type 'MetaProps'.
2. 将 const meta: MetaProps = matches[matches.length - 1].data;
改为 const meta = matches[matches.length - 1].data as MetaProps;
// 定义 MetaProps 接口
interface MetaProps {
activeMenu: string;
}
// 模拟 matches 数组
const matches = [
{
data: 123 // 这里 data 是 number 类型,不符合 MetaProps 类型
}
];
// 使用类型注解
// const meta: MetaProps = matches[matches.length - 1].data;
// console.log(meta.activeMenu);
// 改为类型断言
const meta = matches[matches.length - 1].data as MetaProps;
console.log(meta.activeMenu);
分析
- 类型注解(原代码):使用类型注解时,编译器会严格检查
data
的类型,由于data
是number
类型,不符合MetaProps
类型,编译器会报错,代码无法通过编译。 - 类型断言(修改后代码):改为类型断言后,编译器会绕过类型检查,直接将
data
视为MetaProps
类型。虽然代码可以通过编译,但在运行时,由于data
实际上是number
类型,访问activeMenu
属性会导致运行时错误,例如TypeError: Cannot read properties of undefined (reading 'activeMenu')
。
综上所述,类型断言和类型注解有着不同的类型检查机制,在使用时需要根据具体情况选择合适的方式,以确保代码的正确性和安全性。
Type 'unknown' is not assignable to type 'MetaProps'.
/react/hooks-admin-pro源码/Hooks-Admin-Pro-master/src/layouts/components/Menu/index.tsx:70:11
useEffect(() => {
// const meta = matches[matches.length - 1].data as MetaProps;
const meta: MetaProps = matches[matches.length - 1].data;
类型注解 将第一行改为第二行,这里说的是右侧的matches[matches.length - 1].data unknown值给meta的时候严格检查不匹配
类型断言 正确是第一行的不会对matches[matches.length - 1].data 的MetaProps类型和const meta:any进行比较