TS类型的集合表示
2024-01-28 本文已影响0人
海豚先生的博客
union types 联合类型
image.png image.png image.pngtype CanCross = "green" | "orange";
type ShouldStop = "orange" | "red";
let canCross = "orange" as CanCross; // ✅
let shouldStop = "orange" as ShouldStop; // ✅
unknow 类型,是所有类型的父集
image.pnglet something: unknown;
something = "Hello"; // ✅
something = 2; // ✅
something = { name: "Alice" }; // ✅
something = () => "?"; // ✅
A | unknown = unknown
A & unknown = A
交集,对象的交集就是包含2个对象中的所有类型
image.png image.pngnever类型,string & number = never
image.pngA | never = A
A & never = never
any类型,TS最差实践,是所有类型的父集,也是所有类型的子集
image.pngA | any = any
A & any = any