Specifying Typescript Union Type allowed values for props using Exclude
Jiří Procházka on October 24, 2022
Today I show you how to use generic Typescript Union Types for defining props, but specifying (narrowing) the allowed values.
In Vue 3 using Typescript there is a possibility to define prop Typescript type with PropType<T>.
Let's say we are writing a button component which can have one of predefined sizes: xs, sm, base, lg.
<script setup lang="ts">
import type { PropType } from "vue"
defineProps({
color: {
type: String as PropType<'xs' | 'sm' | 'base' | 'lg'>
}
})
</script>
We can define an universal Union Type with all sizes we use in our lib:
export type UISize = "xs" | "sm" | "base" | "md" | "lg" | "xl";
But we don't want the button to allow xs and xl sizes. They are proper sizes for icons let's say, but our button would be too small or too large.
We can use Exclude on union type to exclude the values we don't want:
<script setup lang="ts">
import type { PropType } from "vue"
defineProps({
color: {
type: String as PropType<Exclude<UISize, 'xs' | 'xl'>>
}
})
</script>
Now our button is using universal UISize type, but with exact allowed values specified.
Simple as that.
Subscribe to Newsletter
If you like my tips, subscribe to my newsletter to catch every article!
I won't spam you more often than once a week with an article link.
Hire Me!
I'm
available
for a
long-term contract
Subscribe to Newsletter
Do you like these articles?
Subscribe to my e-mail newsletter to get notified about new awesome stuff!