簡體   English   中英

將屬性限制為其他屬性的 object 數組中定義的值?

[英]Restrict property to values defined in other property's object array?

給定

type Props= {
  defaultTab?: string;
  tabs?: {
    id: string;
    // ...
  }[];
};

我想更新defaultTab的定義,以將可能的值限制為tabs[].id中包含的值。 例如,如果選項卡是由 ID 為onetwothree的調用者提供的,那么調用者應該只能為defaultTab屬性(或者 null/undefined )提供onetwothree

我試圖這樣做,但無法到達那里......

defaultTab?: Props['tabs']['id'];

但是id沒有在Props['tabs']上定義,這是真的,它是在該數組中的對象上定義的。 不確定如何引用數組中定義的對象。

這是可能的——但它需要破解。

首先,使您的Props通用。 這是在tabsdefaultTab之間建立關系所必需的。

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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM