为什么这些结构相似的类型会不兼容?

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

如果我声明以下类型。

export type Type1 = { id: string } | { id: number };
export type Type2 = { id: string } | { id: number };

为什么当我用下面的方式使用时,我会得到一个错误。

function displayItem(item: Type1) {
  loadItem({ id: item.id });          // error is indicated here
}

function loadItem(item: Type2) {}

enter image description here

我的理解是 { id: number }; export type Type2 = { id: string } 是,它们应该是等价的,因为它们在结构上是相同的。

根据答案进行更简单的重述(不需要第二个类型)。

export type Type1 = { id: string } | { id: number };

function displayItem(item: Type1) {
   loadItem({ id: item.id });          // error is indicated here
}

function loadItem(item: Type1) {}
typescript
1个回答
© www.soinside.com 2019 - 2024. All rights reserved.