Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Type 'string' is not assignable to type '"value1" | "value2" | undefined' (union type)

I have a union type in Vue, which is optional (with the ? character )

(Edit: forgot to rename "MyInterface" to Props)

interface Props{
    setting?: 'value1' | 'value2'
}

const props = withDefaults(defineProps<Props>(), {
    setting: 'value1'
});

In the parent component, I pass downa variable set to a value that matches one of the union members:

    const setting = 'value1';
</script>

<template>

    <MyComponent :setting="setting" />        

But the ":setting" property has the error:

 Type 'string' is not assignable to type '"value1" | "value2" | undefined'  

If I would hardcode a string, the error goes away:

:setting="'value1'" 
like image 595
Galivan Avatar asked Feb 21 '26 06:02

Galivan


1 Answers

As per your interface definition, You are assigning 'value1' | 'value2' as a data type for a setting prop But if you see you are assigning a string type value in a component property. That's the reason it is giving you a syntax error.

It should be :

interface Props{
    setting?: string
}

const props = withDefaults(defineProps<Props>(), {
    setting: 'value1'
});

Here is the official documentation link for more understanding.

like image 97
Creative Learner Avatar answered Feb 23 '26 20:02

Creative Learner



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!