Vue component's props quirks while working with TypeScript

longoandrea

Andrea

Posted on May 27, 2023

Vue component's props quirks while working with TypeScript

Vue and TypeScript, such a complicated relationship! 🤯

A common pitfall comes while defining component's props, which are defined through a structure that provide a sort of "lightweight" type checking for props validation.

This can generate some misunderstandings, it doesn't actually work as type checker, since those type checks and validators are runtime guards, this explains why the type property supports just the native objects (Runtime Type Checks).

Let's add TypeScript

What I said above it doesn't change if you add TypeScript on the equation, those runtime validators still exists and required. So, maybe you might expect to write something like:

<script setup>
type MyCustomType = 'Hello' | 'World'
const props = defineProps({
  myProps: {
    type: MyCustomType
  }
})
// ...
</script>
Enter fullscreen mode Exit fullscreen mode

The code above will results in:

TypeScript error

This happens because you're trying to mix runtime validations with static type checking.

Solution 1

You can fully rely on TypeScript checking:

type MyCustomType = 'Hello' | 'World'
const props = defineProps<{
    test: MyCustomType
}>()
// ...
</script>
Enter fullscreen mode Exit fullscreen mode

In this way you have solved the error, but you won't be able to provide custom validators.

Solution 2

Rely on type assertions:

type MyCustomType = 'Hello' | 'World'
const props = defineProps({
  myProps: {
    type: String as PropType<MyCustomType>
    validator: (value: MyCustomType) => {
       // your custom validation
    },
  }
})
// ...
</script>
Enter fullscreen mode Exit fullscreen mode

Conclusion

As shown above, Vue might seem a little bit tricky while working alongside TypeScript, though it has taken steps onward, and still does.

💖 💪 🙅 🚩
longoandrea
Andrea

Posted on May 27, 2023

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related