Quantcast
Channel: Active questions tagged svelte - Stack Overflow
Viewing all articles
Browse latest Browse all 1541

Create a TypeScript generic type that extends another generic type

$
0
0

I am trying to create a Svelte component that displays hierarchical data. This component, named for now HierarchicalBar renders itself by using the data tree provided. The data tree provided looks like this:

export type NodeItem<T extends NodeItem<T>> = {    id: number;    text: string;    nodes?: T[]};

This type is used to type the nodes prop:

<script lang="ts" generics="TNode extends NodeItem<TNode>">    export let nodes: TNode[];    ...</script>

This is so the correct item type shows up in the variable inside the slot:

{#each nodes as node (node.id)}    ...<slot {node} />    ...{/each}

This part works fine.

Now I want to specialize HierarchicalBar to produce menu bars. So I create a new component named MenuToolbar. For this component, I would like to repeat the pattern above, with one addition: The type of hierarchical data must comply with NodeItem<T> because MenuToolbar will use HierarchicalBar.

This type I cannot produce, so I cannot show and is the objective of this question.

Expected result: A MenuItem TS type that extends NodeItem and is meant itself to be extended just like NodeItem<T>.

Let me know if I should explain anything else. Thanks in advance.


Viewing all articles
Browse latest Browse all 1541

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>