gpt4 book ai didi

javascript - 如何在动态接口(interface)中访问泛型类型属性

转载 作者:行者123 更新时间:2023-11-28 03:14:19 26 4
gpt4 key购买 nike

我想访问接口(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}>;
}

发送到 func 的 prop 示例:

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

关于javascript - 如何在动态接口(interface)中访问泛型类型属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59783974/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com