为什么 & 和 extends 在打字稿中不同

问题描述 投票:0回答:1

下面这两段代码有什么区别?为什么它们不一样?我明白 b.a 和 c.a 的类型都应该是数字。

interface A {
  a: any
}
type B = A & {a: number}

const b = {} as unknown as B;
b.a;

enter image description here

interface A {
  a: any
}

interface C extends A {
  a: number
}

const c = {} as unknown as C;
c.a;

enter image description here

我的理解有误吗? AI 的响应符合我的理解,即两者都应该是数字类型。

我使用了ChatGPT,但它并没有帮助我解决问题。我的 TypeScript 版本是 4.9.5。

typescript
1个回答
0
投票

在第一个示例中,交集类型

a
的类型为
any & number
,并简化为
any

© www.soinside.com 2019 - 2024. All rights reserved.