当前位置:首页 > 服务端 > Difference between extending and intersecting interfaces in TypeScript?

Difference between extending and intersecting interfaces in TypeScript?

Asked 3 years, 7 months ago
Modified 10 months ago
Viewed 18k times
 
88

Let's say the following type is defined:

interface Shape {
  color: string;
}

Now, consider the following ways to add additional properties to this type:

Extension

interface Square extends Shape {
  sideLength: number;
}

Intersection

type Square = Shape & {
  sideLength: number;
}

What is the difference between both approaches?

And, for sake of completeness and out of curiosity, are there other ways to yield comparable results?

1 Answer

98
 

Yes there are differences which may or may not be relevant in your scenario.

Perhaps the most significant is the difference in how members with the same property key are handled when present in both types.

Consider:

interface NumberToStringConverter {
  convert: (value: number) => string;
}

interface BidirectionalStringNumberConverter extends NumberToStringConverter { convert: (value: string) => number; } 

The extends above results in an error because the derriving interface declares a property with the same key as one in the derived interface but with an incompatible signature.

error TS2430: Interface 'BidirectionalStringNumberConverter' incorrectly extends interface 'NumberToStringConverter'. Types of property 'convert' are incompatible. Type '(value: string) => number' is not assignable to type '(value: number) => string'. Types of parameters 'value' and 'value' are incompatible. Type 'number' is not assignable to type 'string'. 

However, if we employ intersection types

type NumberToStringConverter = {
  convert: (value: number) => string;
}

type BidirectionalStringNumberConverter = NumberToStringConverter & { convert: (value: string) => number; } 

There is no error whatsoever and further given

// And this is a good thing indeed as a value conforming to the type is easily conceived
const converter: BidirectionalStringNumberConverter = {
    convert: (value: string | number) => { return (typeof value === 'string' ? Number(value) : String(value)) as string & number; // type assertion is an unfortunately necessary hack. } } const s: string = converter.convert(0); // `convert`'s call signature comes from `NumberToStringConverter` const n: number = converter.convert('a'); // `convert`'s call signature comes from `BidirectionalStringNumberConverter` 

Playground Link

This leads to another interesting difference, interface declarations are open ended. New members can be added anywhere because multiple interface declarations with same name in the same declaration space are merged.

Here is a common use for merging behavior

lib.d.ts

interface Array<T> {
  // map, filter, etc.
}

array-flat-map-polyfill.ts

interface Array<T> {
  flatMap<R>(f: (x: T) => R[]): R[];
}

if (typeof Array.prototype.flatMap !== 'function') { Array.prototype.flatMap = function (f) { // Implementation simplified for exposition. return this.map(f).reduce((xs, ys) => [...xs, ...ys], []); } } 

Notice how no extends clause is present, although specified in separate files the interfaces are both in the global scope and are merged by name into a single logical interface declaration that has both sets of members. (the same can be done for module scoped declarations with slightly different syntax)

By contrast, intersection types, as stored in a type declaration, are closed, not subject to merging.

There are many, many differences. You can read more about both constructs in the TypeScript Handbook. The Interfaces and Advanced Types section are particularly relevant.

  • 2
    Great answer. Thanks for pointing out the difference in behaviour when 'overriding' properties, didn't know about that. That alone is a good reason to use types in certain use cases. Can you point out situations where interface merging is useful? Are there valid use cases when building applications (in other words: not libraries)? 
    –  Willem-Aart
     Oct 6, 2018 at 18:42 
  •  
    Willem Aart as you suggest, it is most useful for writing libraries, but what is an application if not a collection of libraries (including your own app). It can be extremely useful for applications as well. Ex: interface Object {hasOwnProperty<T, K extends string>(this: T, key: K): this is {[P in K]?}} which turns Object.prototype.hasOwnProperty into a type guard by introducing an additional, more specific signature for it. . 
    –  Aluan Haddad
     Oct 6, 2018 at 19:12 
  • 1
    @AluanHaddad the StringToNumberConverter type should be instead named BidirectionalStringNumberConverter, correct? It seems like the other instances were possibly renamed... 
    –  Karl Horky
     Jul 4, 2019 at 19:56
  • 1
    @NathanChappell thank you for catching that. I don't know when that broke. I've updated the example to make it compile, but it now requires a type assertion. I will look into this more. 
    –  Aluan Haddad
     Sep 22, 2020 at 8:37
  • 1
    @AluanHaddad thanks. TS seems to be changing quite fast, so it's probably impossible to keep up with it (especially since they seem to have abandoned maintaining a specification...)   Sep 22, 2020 at 8:47

来源链接:https://www.cnblogs.com/sexintercourse/p/16318398.html

版权声明:
1、Java侠(https://www.javaxia.com)以学习交流为目的,由作者投稿、网友推荐和小编整理收藏优秀的IT技术及相关内容,包括但不限于文字、图片、音频、视频、软件、程序等,其均来自互联网,本站不享有版权,版权归原作者所有。

2、本站提供的内容仅用于个人学习、研究或欣赏,以及其他非商业性或非盈利性用途,但同时应遵守著作权法及其他相关法律的规定,不得侵犯相关权利人及本网站的合法权利。
3、本网站内容原作者如不愿意在本网站刊登内容,请及时通知本站(javaclubcn@163.com),我们将第一时间核实后及时予以删除。





本文链接:https://www.javaxia.com/server/125553.html

分享给朋友:

“Difference between extending and intersecting interfaces in TypeScript?” 的相关文章