Issue
I'm working on a vue3 project with TS and come across this error:

I have 3 potential values coming from my backend and my kind prop is looking for one of those 3 values as a string.
The prop itself looks like:
kind: { type: String as PropType<'AOI' | 'DIMM' | 'FAN'> }
Any idea as to why this error happens? The backend will only ever send one of those 3 values anyway, so I would assume this wouldn't be an issue.
Please let me know if you need anymore context!
Cheers!
Solution
You could extract the strings into a type (as pointed out by @Alexey's answer), and export the type from the component so that callers can use it to declare 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>
Callers of this component could use type assertion (ref('myString' as KindType)) to tell TypeScript to treat any string as a KindType, as seen below. A disadvantage here is this allows invalid strings (i.e., not one of the KindType strings), which could lead to unexpected behavior.
<!-- 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 allows any string
</script>
<template>
<MyComponent :kind="kind" />
</template>
A more robust solution is to pass a type argument to ref, using ref<KindType>('myString'). This enables a helpful compiler error when the string value is invalid.
<script setup lang="ts">
import { ref } from 'vue'
import MyComponent, { type KindType } from './components/MyComponent.vue'
const kind = ref<KindType>('FAN') // ✅ allows only KindType strings
</script>
<template>
<MyComponent :kind="kind" />
</template>
Answered By - tony19
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.