我不確定這是問這個條件問題的正確地方,但我們可以在 TypeScript 中做一般型別嗎?我經常有如下組件:
type Props = {
title: string
buttonLabel?: string
onButtonClick?: () => void
}
所以我可以選擇為按鈕提供一個字串,如果提供了它,那么我還應該提供點擊時發生的事情。但是onButtonClick,如果提供了 buttonLabel,我想是強制性的。一些語法如:
type Props = {
title: string
buttonLabel?: string
onButtonClick<!buttonLabel>: () => void
}
這在 Typescript 或任何其他語言中可用嗎?
uj5u.com熱心網友回復:
我會將省略兩者的型別與需要兩者的型別結合起來
type Props = {
title: string;
} | {
title: string;
buttonLabel: string;
onButtonClick: () => void;
}
uj5u.com熱心網友回復:
如果我理解正確,您可以通過創建另一個這樣的物件來使 buttonLable 和 onButtonClick 成為強制性的:
type Props = {
title: string
buttonLink?: string
buttonData?: {label: string
onButtonClick: () => void
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/369135.html
