My team is building a Vue 3 component library. As the project goes larger in scale, we refactored it with typescript to get a better developing experience.
But here's the thing - there are teams using our lib in different environments, with or without typescript and bundler, which means for almost every component we need to validate prop types both in compile-time and runtime.
props: {
someProp: {
type: String as PropType<'enum1' | 'enum2' | 'enum3'>,
validator: (v: string) => {
return ['enum1', 'enum2', 'enum3'].includes(v)
}
}
}
The code runs well. Teams using typescript are happy - they got their code completion and can spot potential errors ahead of time. Teams using javascript are happy - they can discover any type-related errors at runtime thanks to the validator
. But we are not happy, since the code is duplicated. Technically <'enum1' | ...>
is a type def and ['enum1', ...]
is an array, they are not the same thing - but we literally write the same string multiple times.
Is there any way to implement something that can define a prop with PropType
and validator
without having to reeeeeeepeat myself?