type TabWithSetIndex = (props: TabContentProps) => React.ReactElement;
type TabWithoutSetIndex = () => React.ReactElement;
interface ProjectCardProps {
tabs: Array<{
tabContent: TabWithSetIndex | TabWithoutSetIndex;
}>;
}
游樂場鏈接
如何驗證tabContent是型別TabWithSetIndex還是TabWithoutSetIndex?
uj5u.com熱心網友回復:
幾個選項供您選擇:
length帶有型別謂詞的函式- 有區別的聯合(有或沒有型別謂詞)
length帶有型別謂詞的函式
您可以使用如下型別謂詞來執行此操作:
function isTabWithoutSetIndex(
tabContent: TabWithSetIndex | TabWithoutSetIndex
): tabContent is TabWithoutSetIndex {
return tabContent.length === 0;
}
(length函式的屬性,粗略地說,是它所宣告的沒有默認值的形式引數的數量。)
然后,當您查看特定的tab.tabContent時,您會:
if (isTabWithoutSetIndex(tab.tabContent)) {
// It's `TabWithoutSetIndex`
tab.tabContent();
} else {
// It's `TabWithSetIndex`
tab.tabContent({x: "foo"});
}
游樂場鏈接
也就是說,我擔心使用該函式length,因為這是一個完全有效的函式,TabWithSetIndex它具有:length0
function thisIsATabWithSetIndex(...args[]) {
// ...
}
...因為其余引數不計入length.
有區別的聯合(有或沒有型別謂詞)
為避免使用length,您可以使用有區別的 union,如下所示:
type TabWithSetIndex =
((props: TabContentProps) => React.ReactElement) &
{ __type__: "withSetIndex"; };
type TabWithoutSetIndex =
(() => React.ReactElement) &
{ __type__: "withoutSetIndex" };
然后,您將擁有實用程式函式來設定__type__屬性呼叫者將通過以下方式傳遞其函式:
function makeWithSetIndexFunction(
fn: (props: TabContentProps) => React.ReactElement
): TabWithSetIndex {
return Object.assign(fn, {__type__: "withSetIndex"}) as TabWithSetIndex;
}
function makeWithoutSetIndexFunction(
fn: () => React.ReactElement
): TabWithoutSetIndex {
return Object.assign(fn, {__type__: "withoutSetIndex"}) as TabWithoutSetIndex;
}
然后要么直接測驗__type__:
if (tab.tabContent.__type__ === "withoutSetIndex") {
// It's `TabWithoutSetIndex`
tab.tabContent();
} else {
// It's `TabWithSetIndex`
tab.tabContent({x: "foo"});
}
...或者使用現在更可靠的型別謂詞:
function isTabWithoutSetIndex(
tabContent: TabWithSetIndex | TabWithoutSetIndex
): tabContent is TabWithoutSetIndex {
return tabContent.__type__ === "withoutSetIndex";
}
游樂場鏈接
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/514947.html
標籤:打字稿
上一篇:Angular:如何為時間欄位添加固定冒號并自動跳過它?
下一篇:創建只需要指定欄位的型別
