如何在动态接口中访问泛型类型属性



我想在接口中访问动态 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}>;
}

道具发送到函数的示例:

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具有属性someProperty(Record是内置类型(。

//                           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
}

样本

最新更新