仅基于此声明:
const state = reactive({
user: {
uid: "",
provider: string[],
}
});
您编写它的目的是为provider 属性赋予string[] 的类型,但在此语句中它试图设置变量的值(而不是类型),因为string[] 不是一个值,它会抛出错误。要将provider 的值设置为具有string[] 类型的数组,您可以使用:
const state = reactive({
user: {
// initialize as "", type is automatically set to string
uid: "",
// create array and override its type to an array of strings
provider: [] as string[],
}
});
但是,当我们查看您如何使用这个 state 变量时:
const user = auth.currentUser;
if (user != null) {
state.user.uid = user.uid || "";
user.providerData.forEach(function(profile) {
state.user.provider.push({ // <-- this bit here is important
providerId: profile.providerId,
uid: profile.uid,
})
});
}
在这些行中,您将 { providerId: string, uid: string } 类型的对象推送到您的 state.user.provider 数组。这意味着您的第一段代码实际上需要:
const state = reactive({
user: {
// initialize as "", the type is automatically set to string
uid: "",
// create empty array and override its type to an array of { providerId: string, uid: string } objects
provider: [] as ({ providerId: string, uid: string })[],
}
});
您也可以使用接口来命名此对象形状:
interface ProviderData {
providerId: string;
uid: string;
}
// you could also use this similar syntax:
// type ProviderData = {
// providerId: string;
// uid: string;
// }
const state = reactive({
user: {
// initialize as "", the type is automatically set to string
uid: "",
// create empty array and override its type to an array of ProviderData objects
provider: [] as ProviderData[],
}
});