I would like to access dynamic T property in an interface to extend his typing to allow this kind of generic function:
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
}
I use this for now, it works but I don't like the any typing allowing everything on the function prop:
interface SpecialInterface<T> {
someProperty: AnotherType<{[key: string]: any}>;
}
Example of prop send to func :
interface IProp {
someProperty: AnotherType<{prop3: number}>
}
const prop: IProp = {
someProperty: {
prop: true,
prop2: "test",
prop3 : 5
}
}
Any ideas?
I hope it helps you
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
};
You can add a generic constraint T extends Record<"someProperty", any>
to ensure, that T
has property someProperty
( Record
is a built-in type).
// 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
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.