如何使用 `null` 在 Vue 3 和 TypeScript 中定义一个空引用?
How to use `null` to define an empty ref in Vue 3 & TypeScript?
我正在使用 Vue 3 和带有脚本设置标签的 TypeScript (<script setup lang="ts">
.
我经常在可组合项中有一个 ref,如下所示:
const composableMessage = ref<string | null>(null);
它是一个字符串或数字或具有初始“空”值的东西。我故意使用 null
而不是 undefined
来定义“空”,因为我更喜欢它。
然后我有一个带有道具的子组件,如下所示:
defineProps({
messageProp: {
type: String,
required: false,
default: '',
},
});
并且在这样的父组件中使用它时:
import myComposable from '/src/composables/myComposable';
const { composableMessage } = myComposable();
<my-component :messageProp="composableMessage" />
我在 :messageProp
上收到此 TypeScript 错误:
Type 'string | null' is not assignable to type 'string | undefined'.
Type 'null' is not assignable to type 'string | undefined'.ts(2322)
如果我使用 const composableMessage = ref<string | undefined>(undefined);
,TypeScript 错误就会消失,但我宁愿将其保留为 null
。
为什么我被迫使用 undefined
作为空引用?
有办法解决这个问题吗?
恰恰相反,由于 required: false
,您的 messageProp
只接受 string
或 undefined
,但您尝试发送它 string
或 null
.
我作为评论 发送的 link 似乎不适用于 Vue3 和 Volar/Typescript。
所以要接受 null 你应该改变 messageProp
的属性类型如下
defineProps({
messageProp: {
type: String as PropType<string|null>,
required: false,
default: '',
},
});
(注意:我不希望为 null
设置默认值 (''),只有 undefined
,所以您可能需要自己处理空值)
(注2:你不需要写ref<string | undefined>(undefined)
你会得到与ref<string>()
相同的Ref<string|undefined>
对象)
我正在使用 Vue 3 和带有脚本设置标签的 TypeScript (<script setup lang="ts">
.
我经常在可组合项中有一个 ref,如下所示:
const composableMessage = ref<string | null>(null);
它是一个字符串或数字或具有初始“空”值的东西。我故意使用 null
而不是 undefined
来定义“空”,因为我更喜欢它。
然后我有一个带有道具的子组件,如下所示:
defineProps({
messageProp: {
type: String,
required: false,
default: '',
},
});
并且在这样的父组件中使用它时:
import myComposable from '/src/composables/myComposable';
const { composableMessage } = myComposable();
<my-component :messageProp="composableMessage" />
我在 :messageProp
上收到此 TypeScript 错误:
Type 'string | null' is not assignable to type 'string | undefined'.
Type 'null' is not assignable to type 'string | undefined'.ts(2322)
如果我使用 const composableMessage = ref<string | undefined>(undefined);
,TypeScript 错误就会消失,但我宁愿将其保留为 null
。
为什么我被迫使用 undefined
作为空引用?
有办法解决这个问题吗?
恰恰相反,由于 required: false
,您的 messageProp
只接受 string
或 undefined
,但您尝试发送它 string
或 null
.
我作为评论
所以要接受 null 你应该改变 messageProp
的属性类型如下
defineProps({
messageProp: {
type: String as PropType<string|null>,
required: false,
default: '',
},
});
(注意:我不希望为 null
设置默认值 (''),只有 undefined
,所以您可能需要自己处理空值)
(注2:你不需要写ref<string | undefined>(undefined)
你会得到与ref<string>()
相同的Ref<string|undefined>
对象)