簡體   English   中英

Typescript 參考接口自帶屬性

[英]Typescript reference interface own property

我想將接口的屬性類型用作泛型,但我不確定是否支持我想要做的事情。 我用代碼解釋一下:

通常我們可以這樣做:

enum Sections {
  users = 'users',
  projects = 'projects'
}

interface SectionEles {
  [Section.users] : {...};
  [Section.projects]: {...};
}

interface SezViewSettings<S extends Sections> = {
  section: S;
  where: Array<keyof SectionEles[S]>;
}

這很好用,但我想避免使SezViewSettings成為generic的 . 我更願意從分配給屬性section的值中提取S ,如下所示:

interface SezViewSettings = {
  section: S extends Sections;
  where: Array<keyof SectionEles[S]>;
}

這可以做到嗎?

如果沒有 generics,接口就無法表示此約束。

在這種情況下,您可能的S類型是enumerable ,因此您可以為所有可能的S值形成SezViewSettings<S>聯合,並將其用作您的類型。 這可能足以滿足您的需求。

這是一種方法,通過創建一個立即查找其屬性的映射類型

type SezViewSettingUnion = { [S in Section]: SezViewSettings<S> }[Section]
/* type SezViewSettingUnion = SezViewSettings<Section.users> | 
     SezViewSettings<Section.projects>
*/

同樣,您可以使用分布式條件類型

type _SezViewSettingUnion<S extends Section> =
    S extends any ? SezViewSettings<S> : never;
type SezViewSettingUnion = _SezViewSettingUnion<Section>;
/* type SezViewSettingUnion = SezViewSettings<Section.users> | 
SezViewSettings<Section.projects> */

兩者最終產生相同的類型,相當於SezViewSettings<Section.users> | SezViewSettings<Section.projects> SezViewSettings<Section.users> | SezViewSettings<Section.projects>


好的,希望有幫助; 祝你好運!
鏈接到代碼

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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