Hey everyone,
I'm trying to implement an inheritance pattern in TypeScript.
I have this basic type:
export type Component = {
id: number;
name: string;
};
With the following main type:
export interface ComponentsList {
name: string;
components: Record<string, Component>;
}
const listA: ComponentsList = {
name: "list-a",
components: { a: { id: 0, name: "A" }}
}
Now i wanted to make another type, let's call it InheritedComponentsList, that i can use to define an object who inherits the components key from the parent, something like this:
const listA: ComponentsList = {
name: "list-a",
components: {
a: {
id: 0,
name: "A"
}
}
}
const listB: InheritedComponentsList<typeof listA> = {
name: "list-b",
parent: listA,
components: {
// Should give me error telling me "a" is missing from listB components
}
}
I thought i could do something like this:
export interface InheritedComponentsList<T extends ComponentsList> {
name: string;
parent: T;
components: Record<keyof T["components"], Component>;
}
But it's not working...
See TS Playground attached