Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How define an optional prop in svelte with typescript?

I want to declare an optional prop in svelte with typescript, but I get the following error: "Declaration or statement expected". How can I declare the prop correctly?

My Type

export enum MyVariants {
  one = 'one',
  two = 'two'
}

Svelte component

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

<script lang="ts">
  export let variant?: MyVariants;
</script>

Error:

   ts Declaration or statement expected

>Solution :

Caveat: I haven’t used Svelte (yet!)

But according to this answer, the way you make a prop optional in Svelte is to give it a default value (an initializer on the declaration).

So in your case, you’d define explicitly that it could be undefined and assign it a default value of undefined:

<script lang="ts">
  export let variant: MyVariants | undefined = undefined;
</script>

If you’re going to do this a lot, you might want a reusable type like this which perhaps provides some semantic value:

type Optional<T> = T | undefined;

Giving you:

<script lang="ts">
  export let variant: Optional<MyVariants> = undefined;
</script>

TypeScript Playground

And if you want to, you can write undefined as void 0. (I don’t, but I’m often tempted.) That would give you:

<script lang="ts">
  export let variant: Optional<MyVariants> = void 0;
</script>

TypeScript Playground

Or you could have a do-nothing utility function providing both the type and the undefined value:

function optional<T>(): T | undefined {
  return undefined;
}

That would give you:

<script>
let variant = optional<MyVariants>();
</script>

TypeScript Playground

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading