如何在 Vue 3 和 TypeScript 中使用 `null` 定义空引用?

Tin*_*ger 6 typescript vuejs3

我使用 Vue 3 和 TypeScript 以及脚本设置标签 ( <script setup lang="ts">.

我经常在可组合项中有一个引用,如下所示:

const composableMessage = ref<string | null>(null);
Run Code Online (Sandbox Code Playgroud)

它是一个字符串或数字或初始值为“空”的东西。我故意使用null而不是undefined定义“空”,因为我更喜欢它。

然后我有一个带有 prop 的子组件,如下所示:

defineProps({
  messageProp: {
    type: String,
    required: false,
    default: '',
  },
});
Run Code Online (Sandbox Code Playgroud)

当在父组件中使用它时,如下所示:

import myComposable from '/src/composables/myComposable';
const { composableMessage } = myComposable();
<my-component :messageProp="composableMessage" />
Run Code Online (Sandbox Code Playgroud)

我在以下位置收到此 TypeScript 错误:messageProp

Type 'string | null' is not assignable to type 'string | undefined'.
  Type 'null' is not assignable to type 'string | undefined'.ts(2322)
Run Code Online (Sandbox Code Playgroud)

如果我使用const composableMessage = ref<string | undefined>(undefined);TypeScript 错误就会消失,但我宁愿将其保留为null.

为什么我被迫使用undefined空引用?

有没有解决的办法?

joa*_*del 4

相反,您messageProp仅接受stringundefined由于required: false,但您尝试发送它stringnull

我作为评论发送的链接VueJS 使用带有 NULL 和“未定义”值的 Prop 类型验证?似乎不适用于 Vue3 和 Volar/Typescript。

因此,要接受 null,您应该更改 prop 类型,messageProp如下所示

defineProps({
  messageProp: {
    type: String as PropType<string|null>,
    required: false,
    default: '',
  },
});
Run Code Online (Sandbox Code Playgroud)

null(注意:我不希望为, only设置默认值('')undefined,因此您可能需要自己处理 null 值)

(注意2:你不需要写ref<string | undefined>(undefined)你会得到相同的Ref<string|undefined>对象ref<string>()

  • 我认为你是对的,我已经转向“未定义”,因为它与 Typescript 和 Vue Props 中的可选属性配合得更好。 (2认同)