To streamline the process, you can consolidate the strings into a type
(as highlighted by @Alexey in their insightful response). This type
can then be exported from the component to allow users to define their kind
bindings:
<!-- MyComponent.vue -->
<script lang="ts">
import { defineComponent, type PropType } from 'vue';
export type KindType = 'AOI' | 'DIMM' | 'FAN'
export default defineComponent({
props: {
kind: { type: String as PropType<KindType> }
},
})
</script>
Users of this component can utilize type assertion (ref('myString' as KindType)
) to instruct TypeScript to interpret any string as a member of KindType
, as shown below. It's worth noting that this approach permits incorrect strings (i.e., those outside the defined KindType
values), potentially leading to unexpected outcomes.
<!-- App.vue -->
<script setup lang="ts">
import { ref } from 'vue'
import MyComponent, { type KindType } from './components/MyComponent.vue'
const kind = ref('foo' as KindType) // ⛔️ compiles but accepts any string
</script>
<template>
<MyComponent :kind="kind" />
</template>
A more effective solution involves supplying a type argument to ref
, such as ref<KindType>('myString')
. By doing so, the compiler will issue an error if the provided string is not valid.
<script setup lang="ts">
import { ref } from 'vue'
import MyComponent, { type KindType } from './components/MyComponent.vue'
const kind = ref<KindType>('FAN') // ✅ restricts input to KindType strings only
</script>
<template>
<MyComponent :kind="kind" />
</template>
View a live demonstration here.