Home > database >  svelte typescript component require at least one prop
svelte typescript component require at least one prop

Time:01-08

I would like to create a svelte component that requires at least on prop to be passed to it.

let's say I have a component with two exported props, a and b:

export let a: number | undefined;
export let b: number | undefined;

Passing just a or b should both be allowed:

<Component a={1} />
<Component b={1} />

But passing none should not:

<Component />

The overall type would be something like this:

type Component = {
    a: number
} | {
    b: number
}

But I dont know how to tell svelte this type.

CodePudding user response:

There is a way to specify the property types via $$Props but this tries to reconcile the types with those specified on the exports which can lead to errors. The specifics depend on the TS configuration.

E.g.

<script lang="ts">
    type $$Props =
        { a: number, b?: never } |
        { b: number, a?: never }

    export let a: number | undefined
    export let b: number | undefined
</script>

Maybe you can make that work for your scenario.

RFC for this feature (maybe leave some feedback there)

CodePudding user response:

I think you mean this

type PropsA = {
  a: number;
  b?: never
}

type PropsB = {
  a?: never;
  b: number
}

type Props = PropsA | PropsB

const A: Props = {
  a: 1,
}

const B: Props = {
  b: 1,
}
  • Related