error TS2464: A computed property name must be of type 'string', 'number', 'symbol', or 'any' #10803
-
I have a TypeScript error when using a dynamic attribute on a dynamic component:
The same error is raised for the href attribute. This is the code: <script setup lang="ts">
import { computed } from 'vue';
import type { LocationAsRelativeRaw, RouteRecord } from 'vue-router';
interface Props {
route?: RouteRecord | LocationAsRelativeRaw,
url?: string,
method?: () => void
}
const props = defineProps<Props>();
const tag = computed(() => props.route ? 'router-link' : 'a');
const to = computed(() => props.route ? 'to' : null);
const href = computed(() => props.url ? 'href' : null);
const click = computed(() => props.method ? 'click' : null);
</script>
<template>
<component
:is="tag"
:[to]="route"
:[href]="url"
@[click]="method"
>
<slot />
</component>
</template>
<style scoped>
</style> How do I solve this error? |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
const to = computed(() => props.route ? 'to' : ''); However, if your intention is to add the attributes only if you have included them in the props. I think you can just specify them normally like this, because if the bound value is <script setup lang="ts">
interface Props {
route?: RouteRecord | LocationAsRelativeRaw
url?: string
method?: () => void
}
const props = defineProps<Props>()
const tag = computed(() => props.route ? 'router-link' : 'a')
</script>
<template>
<component
:is="tag"
:to="route"
:href="url"
@click="method"
>
<slot />
</component>
</template> |
Beta Was this translation helpful? Give feedback.
props
is pretty much an object, so TypeScript is complaining because you're using a value which can benull
as the object property. Changing the falsy value in your ternary operator to an empty string can fix the problem, but I'm not sure if it's ideal.However, if your intention is to add the attributes only if you have included them in the props. I think you can just specify them normally like this, because if the bound value is
null
orundefined
, then the attribute will be removed from the rendered element. Reference: https://vuejs.org/guide/essentials/template-syntax.html#attribute-bindings.