Typescript 中的交集类型是什么?
在 Typescript 中,虽然交集和并集类型相似,但它们的使用方式完全不同。交集类型是一种将多种类型合并为一个的类型。这允许您组合多种类型以创建具有您需要的所有属性的单一类型。这种类型的对象将具有来自所有给定类型的成员。 '&'运算符用于创建交集类型。
示例 1:创建交叉类型:在本示例中,创建了两个名为 student 和 teacher 的接口。交叉类型是通过在学生和教师之间使用“&”创建的。 Intersected 类型包含两个接口的所有属性。创建一个交集类型的 obj 并从中检索值。如果不将属性分配给交集类型对象,我们就无法使用它。
Javascript
interface Student {
student_id: number;
name: string;
}
interface Teacher {
Teacher_Id: number;
teacher_name: string;
}
type intersected_type = Student & Teacher;
let obj1: intersected_type = {
student_id: 3232,
name: "rita",
Teacher_Id: 7873,
teacher_name: "seema",
};
console.log(obj1.Teacher_Id);
console.log(obj1.name);
Javascript
interface A {
feauA: string;
feauB: string;
}
interface B {
feauA: number;
feauB: string;
}
type AB = A & B;
let obj1: AB;
let obj2: AB;
// Error, Type '20' is not assignable
// to type 'string & number'
obj1.feauA = 20;
console.log(obj1.feauA);
obj2.feauB = "c";
console.log(obj2.feauB);
Javascript
interface A {
prop1: String;
}
interface B {
prop2: String;
}
interface C {
prop3: String;
}
let obj1: A & B = { prop1: "length", prop2: "width" };
let obj2: B & A = { prop1: "length", prop2: "width" };
let obj3: A & (B & C) = { prop1: "", prop2: "", prop3: "" };
let obj4: (A & B) & C = { prop1: "", prop2: "", prop3: "" };
obj3.prop3 = "height";
console.log(obj3.prop3);
obj4.prop1 = "length";
console.log(obj4.prop1);
console.log(obj3 == obj4); // false
console.log(typeof obj3 == typeof obj4); // true
console.log(typeof obj1 == typeof obj2); // true
输出:
7873
rita
示例 2:在此示例中,我们创建了两个接口 A 和 B,其中有两个属性名为“feauA”和“feauB”。但是两个接口中 feauA 的类型并不相同,当我们尝试将值 20 分配给 feauA 时,打字稿编译器会引发错误,因为交集类型是“字符串和数字”类型。如果我们尝试将字符串分配给 feauA,则不会引发关于何时相交类型为 String 的错误。
Javascript
interface A {
feauA: string;
feauB: string;
}
interface B {
feauA: number;
feauB: string;
}
type AB = A & B;
let obj1: AB;
let obj2: AB;
// Error, Type '20' is not assignable
// to type 'string & number'
obj1.feauA = 20;
console.log(obj1.feauA);
obj2.feauB = "c";
console.log(obj2.feauB);
输出:
error TS2322: Type 'number' is not assignable to type 'never'.
obj1.feauA = 20;
// Error, Type '20' is not assignable
// to type 'string & number'
示例 3:交集类型是可交换的和关联的:当我们与两个或多个类型相交时,交集的顺序无关紧要。即使相交的顺序改变了相交对象的类型相同,使用'typeof'运算符来检查相交对象的属性也相同。
commutative property: A&B = B&A
associative property: (A&B)&C = A&(B&C)
Javascript
interface A {
prop1: String;
}
interface B {
prop2: String;
}
interface C {
prop3: String;
}
let obj1: A & B = { prop1: "length", prop2: "width" };
let obj2: B & A = { prop1: "length", prop2: "width" };
let obj3: A & (B & C) = { prop1: "", prop2: "", prop3: "" };
let obj4: (A & B) & C = { prop1: "", prop2: "", prop3: "" };
obj3.prop3 = "height";
console.log(obj3.prop3);
obj4.prop1 = "length";
console.log(obj4.prop1);
console.log(obj3 == obj4); // false
console.log(typeof obj3 == typeof obj4); // true
console.log(typeof obj1 == typeof obj2); // true
输出:
height
length
false
true
true
参考: https://www.typescriptlang.org/docs/handbook/unions-and-intersections.html#intersection-types