[英]Restrict property to values defined in other property's object array?
給定
type Props= {
defaultTab?: string;
tabs?: {
id: string;
// ...
}[];
};
我想更新defaultTab
的定義,以將可能的值限制為tabs[].id
中包含的值。 例如,如果選項卡是由 ID 為one
、 two
和three
的調用者提供的,那么調用者應該只能為defaultTab
屬性(或者 null/undefined )提供one
、 two
或three
。
我試圖這樣做,但無法到達那里......
defaultTab?: Props['tabs']['id'];
但是id
沒有在Props['tabs']
上定義,這是真的,它是在該數組中的對象上定義的。 不確定如何引用數組中定義的對象。
這是可能的——但它需要破解。
首先,使您的Props
通用。 這是在tabs
和defaultTab
之間建立關系所必需的。
type Props<T extends string>= {
defaultTab?: T;
tabs?: {
id: T;
// ...
}[];
};
declare class MyComponent<T extends string> extends React.Component<Props<T>> {};
我們還沒有完成。 如果你這樣做:
<MyComponent tabs={[{ id: 'foo' }, { id: 'bar' }]} defaultTab="potato" />
它將編譯,因為defaultTab
的允許值將包括我們傳遞給defaultTab
的任何內容! 我們需要告訴 TypeScript defaultTab
應該取決於我們在tabs
中提供的任何內容。 換句話說,我們要告訴 TypeScript:首先,看看tabs
。 只有這樣才能推斷defaultTab
可以是什么。
/**
* @see https://github.com/microsoft/TypeScript/issues/14829#issuecomment-504042546
*/
type DeferTypeInference<T> = [T][T extends any ? 0 : never];
type Props<T extends string>= {
defaultTab?: DeferTypeInference<T>;
tabs?: {
id: T;
// ...
}[];
};
declare class MyComponent<T extends string> extends React.Component<Props<T>> {};
現在它起作用了!
<MyComponent tabs={[{ id: 'foo' }, { id: 'bar' }]} defaultTab="bar" /> // OK
<MyComponent tabs={[{ id: 'foo' }, { id: 'bar' }]} defaultTab="potato" /> // Compile-time error
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.