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
<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>
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>
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>