Johannes Buchholz
Johannes Buchholz

Reputation: 2277

Type a Svelte components property based on another properties value

In the svelte component

<script lang="ts">
    export let multiple: boolean = false;
    export let value: string|string[];

    // ...
</script>

<!-- ... -->

the type of the value property should be string if multiple == false and string[] otherwise. How can this be achieved?

Edit: The idea is to get a Discriminated Union effect for components.

Upvotes: 3

Views: 972

Answers (1)

Andrew1325
Andrew1325

Reputation: 3579

You need to make the type of 'value' a conditional type. To do this you should declare a function that will determine and return the type for you. This can be done like so:

declare function f<T extends boolean>(x: T): T extends false ? string : string[];

Then you can have your props defined and the type of 'value' will be set to string unless the component declaration sets 'multiple' to true where the type of 'value' will become string[].

export let multiple: boolean = false;
export let value = f(multiple);

Upvotes: 1

Related Questions