可以創建具有多個屬性的介面,如果使用其中一個,還需要另一個?
例如 :
interface MyProps {
onPressAll: () => void;
icon?: ImageSourcePropType;
onPressIcon?: () => void;
}
我想要的是:如果設定了圖示,則需要onPressIcon(反之亦然),否則不應使用任何人。
例如,當我呼叫我的組件時:
<MyComponent
onPressAll={() => {}}
icon={myIcon}
/>
// This should return an error because onPressIcon is missing
<MyComponent
onPressAll={() => {}}
onPressIcon={() => {}}
/>
// This should return an error because icon is missing
<MyComponent
onPressAll={() => {}}
/>
// Good
<MyComponent
onPressAll={() => {}}
onPressIcon={() => {}}
icon={myIcon}
/>
// Good
謝謝 !
uj5u.com熱心網友回復:
你不能用界面來做到這一點。您需要使用聯合:
type MyPropsCommon = {
onPressAll: () => void;
}
type MyProps = MyPropsCommon & (
| { icon?: undefined, onPressIcon?: undefined}
| {
icon: ImageSourcePropType;
onPressIcon: () => void;
})
游樂場鏈接
uj5u.com熱心網友回復:
使用區分聯合。
interface PropsWithIcons {
onPressAll: () => void;
hasIcon: true
icon: ImageSourcePropType;
onPressIcon: () => void;
}
interface PropsWithoutIcons {
hasIcon: false
onPressAll: () => void;
}
type MyProps = PropsWithIcons | PropsWithoutIcons
var obj: MyProps = {} as MyProps
if (obj.hasIcon) {
console.log(obj.icon, obj.onPressIcon)
}
else {
console.log(obj.icon, obj.onPressIcon) // errors
}
操場
uj5u.com熱心網友回復:
你可以只擴展介面:
interface MyCommonProps
{
onPressAll: () => void;
}
interface MyIconProps extends MyCommonProps
{
icon: ImageSourcePropType;
onPressIcon: () => void;
}
您還可以組合型別,以便需要所有屬性:
interface MyOtherProps
{
other: number;
}
type MyProps = MyIconProps & MyOtherProps;
選擇適合你的目的。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/510422.html
標籤:打字稿类型
上一篇:打字稿從類引數的值中創建型別
