簡體   English   中英

如何在動態接口中訪問泛型類型屬性

[英]How to access generic type property in dynamic interface

我想在接口中訪問動態 T 屬性以擴展他的類型以允許這種通用函數:

type AnotherType<T extends {}> = T & {
    prop: boolean;
    prop2: string;
};

interface SpecialInterface<T> {
    someProperty: AnotherType<{T["someProperty"]}>; // I know what key of T I want to extends but can't understand how
}

const func = <T extends SpecialInterface<T>>(prop: T) => {
    const a = prop.someProperty.prop; // I would like no error on this
    // somethings
}

我現在使用它,它可以工作,但我不喜歡允許函數道具上的所有內容的任何類型:

interface SpecialInterface<T> {
    someProperty: AnotherType<{[key: string]: any}>;
}

prop 發送到 func 的示例:

interface IProp {
    someProperty: AnotherType<{prop3: number}>
}

const prop: IProp = {
    someProperty: {
        prop: true,
        prop2: "test",
        prop3 : 5
    }
}

有任何想法嗎?

我希望它能幫助你

interface Another {
    key: number;
    value: string;
}

interface ExtraAnother extends Another {
    someProperty: number;
}

interface SpecialInterface<T extends Another> {
    someProperty: T
};

const func = (prop: SpecialInterface<ExtraAnother>) => {
    const a = prop.someProperty; // I would like no error on this
    // somethings
};

您可以添加通用約束T extends Record<"someProperty", any>以確保T具有屬性somePropertyRecord是內置類型)。

//                           v  add this constraint
interface SpecialInterface<T extends Record<"someProperty", any>> {
    someProperty: AnotherType<T["someProperty"]> // works
}

const func = <T extends SpecialInterface<T>>(prop: T) => {
    const a = prop.someProperty.prop; // works
}

樣本

暫無
暫無

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

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