简体   繁体   English

TypeScript 接口反应

[英]TypeScript interfaces React

How can I use one of the two interfaces for the same object?如何将两个接口之一用于同一个 object? For example:例如:

interface one {
  id: string
  color: string
}

interface two {
  id: string
  numb: number
}

I have an "Item" component that receives an "item" object.我有一个接收“项目”object 的“项目”组件。 This object can be of type "one" or of type "two".这个 object 可以是“一”型或“二”型。 If I specify the type as follows, then an error appears:如果我按如下方式指定类型,则会出现错误:

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

Is there any solution in this case?在这种情况下有什么解决办法吗? Thank you for taking the time!感谢您抽出宝贵时间!

Use extends使用扩展

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 }) => {
///
}

Here's a example这是一个例子

When you use a union type, you need to narrow it via a runtime test to use non-common properties.当您使用联合类型时,您需要通过运行时测试来 缩小它以使用非通用属性。

For instance, in your example, you can use the existence of the color property:例如,在您的示例中,您可以使用color属性的存在:

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

If you're going this route, for clarity I recommend skipping interfaces and using a discriminated union:如果你要走这条路,为了清楚起见,我建议跳过接口并使用有区别的联合:

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.
  } 
}

If you have a type you can't change, and you have a runtime test that is obvious to you that it determines the type of interface, but it's not obvious to the compiler, another thing you can do is a type guard:如果您有一个无法更改的类型,并且您有一个运行时测试对您来说很明显它确定了接口的类型,但对编译器来说并不明显,那么您可以做的另一件事是类型保护:

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