简体   繁体   English

如何用类型扩展 TS 接口?

[英]How to extend a TS interface with a type?

I'm trying to declare types in TSX.我正在尝试在 TSX 中声明类型。 What I would like to have is that if user adds one prop to a component, they can't put the other prop.我想要的是,如果用户将一个道具添加到组件中,他们就不能放置另一个道具。 This works, but I'm using these props in mostly all my components, so I'd like not to repeat this code.这行得通,但我在大部分组件中都使用了这些道具,所以我不想重复这段代码。

I tried to extend one of my component interface with this type, but I get this error:我试图用这种类型扩展我的一个组件接口,但我收到了这个错误:

An interface can only extend an object type or intersection of object types with statically known members.

How could I do?我该怎么办?

This is my code:这是我的代码:

interface PossibleColors1 {
    color?: AllColorsTypes // List of colors
    customColor?: never
}

interface PossibleColors2 {
    color?: never
    customColor?: CustomColorTypes // Any other color
}

type PossibleColorsTypes = PossibleColors1 | PossibleColors2

interface Props extends PossibleColorsTypes { // This is the line not working
    
}

Thanks for your answers!感谢您的回答!

Intersect PossibleColorsTypes with another type instead of extending it with an interface:PossibleColorsTypes与另一种类型相交,而不是用接口扩展它:

interface PossibleColors1 {
    color?: AllColorsTypes // List of colors
    customColor?: never
}

interface PossibleColors2 {
    color?: never
    customColor?: CustomColorTypes // Any other color
}

type PossibleColorsTypes = PossibleColors1 | PossibleColors2

type Props = PossibleColorsTypes & { myNewProperty: "yay" };

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

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