繁体   English   中英

TypeScript 接口反应

[英]TypeScript interfaces React

如何将两个接口之一用于同一个 object? 例如:

interface one {
  id: string
  color: string
}

interface two {
  id: string
  numb: number
}

我有一个接收“项目”object 的“项目”组件。 这个 object 可以是“一”型或“二”型。 如果我按如下方式指定类型,则会出现错误:

const Item: React.FC<{ item: one | two }> = ({ item }) => {
///
}

在这种情况下有什么解决办法吗? 感谢您抽出宝贵时间!

使用扩展

interface One {
    id: string;
    color: string;
}

interface Two {
    id: string;
    num: string;
}

interface Item extends One, Two {}

interface Props {
    item: Partial<Item>
}

const Item: React.FC<Props> = ({ item }) => {
///
}

这是一个例子

当您使用联合类型时,您需要通过运行时测试来 缩小它以使用非通用属性。

例如,在您的示例中,您可以使用color属性的存在:

const Item: React.FC<Props> = ({ item }) => {
  if ('color' in item) {
    // use other "one" properties
  }
}

如果你要走这条路,为了清楚起见,我建议跳过接口并使用有区别的联合:

type one = {
  type: 'one',
  id: string,
  color: string
}

type two = {
  type: 'two',
  id: string,
  numb: number
}

const Item: React.FC<{ item: one | two }> = ({ item }) => {
  if (one.type === 'one') {
    // now it's much more obvious you can use 'one' properties.
  } 
}

如果您有一个无法更改的类型,并且您有一个运行时测试对您来说很明显它确定了接口的类型,但对编译器来说并不明显,那么您可以做的另一件事是类型保护:

function isOne(value: one | two): type is one {
  return listOfOnes.includes(value);
}

// ...

const Item: React.FC<Props> = ({item}) => {
  if (isOne(item)) {
    // type guard means you can use 'one' properties here...
  }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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