简体   繁体   中英

Extends vs Intersection in Typescript

Extended in Typescript is like inheritance in C++.
Intersection in Typescript means that the new object will
have all the members of the intersected classes.

Why do we need intersection when while using extends
keyword we can get all the members of both classes in
the derived class?

What is the use case of intersection where extension
would not be preferred?

https://www.typescriptlang.org/docs/handbook/2/objects.html#intersection-types

They work quite similar, but here are some differences:

  1. extends can be used only with types with statically known members:
type SimpleType = {x: string};
interface SimpleInterface extends SimpleType {} // ok
type ComplexType = {x: string} | {x: number};
// error: An interface can only extend an object type or intersection of object types with statically known members.
interface ComplexInterface extends ComplexType {}

Type intersection is a general type operation that can be performed on any two types and will give a result; extends is limited to interfaces and interface-like types (and classes).

  1. When extending from a parent interface, you are not allowed to create fields with the same name as in parent, but with wider type:
interface Parent {
    x: string | number;
}
interface Child1 extends Parent {
    x: string; // ok
}
interface Child2 extends Parent {
    x: string | number | boolean; // error
}

However, type intersection does not complain:

type IntersectedChild = Parent & {x: string | boolean}; // ok
// IntersectedChild will have property 'x' that is an intersection
// of 'string | number' and 'string | boolean', that is a 'string':
type IntersectedChildX = IntersectedChild['x']; // string
  1. When using extends with classes, child class will actually inherit all implementations of its parent; however type intersection only works on type level, so if you have classes A and B and type C = A & B , C is not a class but just a type, and you will need to somehow manually construct an object that will satisfy the contstraints of C (has all members of A and B with the same visibility levels).

Here is a playground link with examples I put above.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM