我在 Vue3 中输入 ref() 时遇到问题。当尝试定义比 TableHeaders 类型中定义的元素更多的元素时,不会收到打字稿的警告。其他 typeof 工作正常(例如 id: "1" 返回警告)。为什么我在这样定义 ref() 时没有收到警告?
类型:
export type TableHeaders = {
id: number;
title: string;
};
当标题定义错误时,Typescript 不会发出警告
type: "text"
。
<script setup lang="ts">
import HeadRow from "./HeadRow.vue";
import { ref, Ref } from "vue";
import { TableHeaders } from "../../assets/types";
const headers: Ref<TableHeaders[]> = ref([
{
id: 0,
title: "Project",
type: "text", // no warnings!
},
]);
</script>
打字稿警告
type: "text"
,而标题稍后会更改。
<script setup lang="ts">
import HeadRow from "./HeadRow.vue";
import { onMounted, ref, Ref } from "vue";
import { TableHeaders } from "../../assets/types";
const headers: Ref<TableHeaders[]> = ref([]);
onMounted(() => {
headers.value = [
{
id: 0,
title: "Project",
type: "text", // Object literal may only specify known properties, and 'type' does not exist in type 'TableHeaders'
},
];
});
</script>
如果尝试在没有 ref() 的情况下执行此操作,则一切正常(收到警告
type: "text"
)
const headers: TableHeaders[] = [
{
id: 1,
title: "Project",
type: "text",
},
]
在 tsconfig.json 中我打开了
"strict": true
和 "exactOptionalPropertyTypes": true
我还尝试从“vue”导入类型{Ref};并像 Ref
import type { Ref } from "vue";
const headers = ref([
{
id: 0,
title: "Project",
type: "text",
},
]) as Ref<TableHeaders[]>;