Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Typescript: 深入 & 操作符与 extends 的区别 #2

Open
Joyee691 opened this issue Apr 7, 2022 · 0 comments
Open

Typescript: 深入 & 操作符与 extends 的区别 #2

Joyee691 opened this issue Apr 7, 2022 · 0 comments

Comments

@Joyee691
Copy link
Owner

Joyee691 commented Apr 7, 2022

Typescript: 深入 & 操作符与 extends 的区别

全文共 389 字,建议阅读时间 5 min

下面是一个类型拓展的两种常见用法:

// base type
interface Shape {
  color: string;
}

// extension
interface Square1 extends Shape {
  width: number;
}

// intersection
type Square2 = Shape & {
  width: number;
}

Playground Link

看起来没有什么不同对吧?那么看看下面的例子:

interface Square {
  width: number;
}

interface Rectangle1 extends Square {	// Type 'string' is not assignable to type 'number'
  width: string;
  height: string;
}

type Rectangle2 = Square & {	// OK
  width: string;
  height: string;
}

let rectangle: Rectangle2 = {
  width: '10px',		// Type 'string' is not assignable to type 'never'.
  height: '12px'
}

Playground Link

上面的例子用了两种方法拓展了不同类型的 width,我们可以观察到两点区别:

  1. 使用 extends 的时候马上就报错了(line 5)
  2. 使用 & 的时候会将 width 的类型指派为 never,后面我们把 string 类型分配给 never 才报错(line 16)

由此我们可以得到第一个结论:当遇到对象属性类型冲突的时候,& 会给冲突属性 never 类型,而 extends 会直接报错


接下来,我们再看看函数的例子:

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

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

// Named property 'convert' of types 'StringToNumber' and 'NumberToString' are not identical.
interface BidirectionalConvert1 extends StringToNumber, NumberToString {}

// {convert: (value: string | number) => string | number;}
type BidirectionalConvert2 = StringToNumber & NumberToString

Playground Link

自此,我们可以得到第二个结论:当遇到函数类型冲突的时候,& 会联集函数的参数与返回值,而 extends 会直接报错

Reference

Difference between extending and intersecting interfaces in TypeScript?

Interfaces vs Intersections

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant