Internal server error: Error parsing JavaScript expression: Unexpected token (1:2) 不能将类型“true”分配给类型“Numberish | undefined”。 ts-plugin(2322)
1. 简要解释报错原因
在 <svg :style={ width, height }>
中,width
和 height
是字符串类型,而 :style
需要的是一个对象,其中的属性值应该是 Numberish | undefined
类型。直接使用字符串会导致类型不匹配,因此 TypeScript 抛出错误。
解决方案:刚开始想着可以通过将 width
和 height
转换为 CSS 属性的正确格式,或者使用 :style
的字符串形式来避免类型不匹配的问题。推荐使用 :style
的对象形式,并确保属性值是有效的 CSS 样式值。
<template>
<div>
<svg :style="svgStyle">
<use :xlink:href="prefix + name" :fill="color"></use>
</svg>
</div>
</template>
<script setup lang="ts">
import { computed } from 'vue';
defineProps({
prefix: {
type: String,
default: '#icon-'
},
name: String,
color: {
type: String,
default: ''
},
width: {
type: String,
default: '16px'
},
height: {
type: String,
default: '16px'
}
});
const svgStyle = computed(() => ({
width: `${props.width}`,
height: `${props.height}`
}));
</script>
<style scoped></style>
发现仍然报错 -错误信息: 找不到名称“props”。 ts-plugin(2304)
解决方案:在 <script setup>
中,defineProps
返回的 props 需要通过解构或直接引用 props
对象来访问。当前代码中直接使用了 props.width
和 props.height
,但没有正确引入 props
对象,导致 TypeScript 报错。可以通过解构 defineProps
返回的对象或将 defineProps
的返回值赋值给一个变量来正确访问 props。
<template>
<div>
<svg :style="svgStyle">
<use :xlink:href="prefix + name" :fill="color"></use>
</svg>
</div>
</template>
<script setup lang="ts">
import { computed } from 'vue';
const props = defineProps({
prefix: {
type: String,
default: '#icon-'
},
name: String,
color: {
type: String,
default: ''
},
width: {
type: String,
default: '16px'
},
height: {
type: String,
default: '16px'
}
});
const svgStyle = computed(() => ({
width: props.width,
height: props.height
}));
</script>
<style scoped></style>