首页 > 其他分享 >ts中any和unknown的区别

ts中any和unknown的区别

时间:2022-10-28 01:00:07浏览次数:46  
标签:unknown ts let 类型 foo type any

主要区别

unknown和any都是TS中的顶级类型,但主要区别在于:使用any相当于彻底放弃了类型检查,而unknown类型相较于any更加严格,在执行大多数操作之前,会进行某种形式的检查

赋值操作

let foo: any = 123;
console.log(foo.msg); // 符合TS的语法
let a_value1: unknown = foo;   // OK
let a_value2: any = foo;      // OK
let a_value3: string = foo;   // OK


let bar: unknown = 222; // OK 
console.log(bar.msg); // Error
let k_value1: unknown = bar;   // OK
let K_value2: any = bar;      // OK
let K_value3: string = bar;   // Error
  1. foo是any类型,任何操作都是没有类型检查的,因此对其进行任意类型的赋值都是合法的
  2. bar是unknown类型,因此不能确定是否有msg属性,不能通过语法检查,同时unknown类型的值也不能赋值给any和unknown以外的类型变量

联合类型

在联合类型中,unknown类型会吸收任何类型。即如果任一组成类型是unknown,联合类型也会相当于unknown

type UnionType1 = unknown | null;       // unknown
type UnionType2 = unknown | undefined;  // unknown
type UnionType3 = unknown | string;     // unknown
type UnionType4 = unknown | number[];   // unknown

而any更是能吸收unknown类型,如果任一组成类型是any,则联合类型相当于any

type UnionType5 = unknown | any;  // any

交叉类型

type IntersectionType1 = unknown & null;       // null
type IntersectionType2 = unknown & undefined;  // undefined
type IntersectionType3 = unknown & string;     // string
type IntersectionType4 = unknown & number[];   // number[]
type IntersectionType5 = unknown & any;        // any

由于每种类型都可以赋值给unknown类型,所以在交叉类型中包含unknown不会改变结果

标签:unknown,ts,let,类型,foo,type,any
From: https://www.cnblogs.com/guozhiqiang/p/16834487.html

相关文章

  • TS中的 InstanceType函数
    InstanceType函数 文档中介绍:该函数返回(构造)由某个构造函数构造出来的实例类型组成的类型classC{x=0;y=0;}typeT0=InstanceType<typeofC>;......
  • ts实现发布订阅
    interfaceCacheProps{[key:string]:Array<((data:unknown)=>void)>;}classObserver{privatecaches:CacheProps={};on(eventName:string,fn......
  • CF1491F Magnets
    首先\(n_1n_2+s_1s_2-n_1s_2-n_2s_1=(n_1-s_1)(n_2-s_2)\)这样可以发现,如果知道任意一块有磁性的磁铁,可以将它和其他磁铁询问得到另一块磁铁的状态(如果为\(\pm1\)......
  • requests模块及openpyxl模块简介
    昨日内容回顾正则表达式字符组字符组内部字符为并列关系。连续字符用'-'连接。特殊符号开头、结尾、数字、任意字符、字母数字下划线。量词多次、一次、指......
  • requests进阶
    一、图片下载下载图片,需获取到图片的url地址和图片名称,通过向图片url发起请求,之后获取.content注意:.text返回的是Unicode型的数据。.content返回的是bytes型也就是......
  • Python-requests 模块
    requests模块Python中原生的基于网络请求的模块,主要用来发送HTTP请求,简单便捷,效率极高.工作流程:指定url发起请求获取响应数据持久化存储requests请求......
  • Echarts基础
    Echarts步骤初始化varechart=echarts.init(dom节点,主题)定义选项optionvaroption={title标题legend图例color调试版本tooltip提示xAx......
  • D. Problem with Random Tests
    传送门题意:给出一个字符串,然后,从这个字符串中取两个子串s1,s2,要求两个字符串的或最大思路:首先,先去s1从第一个非0开始取整段,记录第一个非0的位置为p1,因为或位数......
  • 选择Visual Components软件的五大理由
    1、更好的性能开发视觉组件是为了充分利用64位Windows环境。这意味着更好的图形、更快的加载时间和更流畅的用户体验。导航大布局是流动的。内存管理不断优化,以提高仿......
  • echarts相关配置(随时添加)
    option--tooltip图层的信息提示框backgroundColor、textStyle:{color、font-size}option-legend图例属性设置(top、right、x、y等)、orient:(vertical、horizontal)option-seri......