3zz*_*zzy 10 firebase typescript vue.js vuejs3 vue-composition-api
TypeScript 新手。我正在尝试设置状态但收到此错误。
错误:'string' only refers to a type, but is being used as a value here.
const state = reactive({
user: {
uid: "",
provider: string[],
}
});
const user = auth.currentUser;
if (user != null) {
state.user.uid = user.uid || "";
user.providerData.forEach(function(profile) {
state.user.provider.push({
providerId: profile.providerId,
uid: profile.uid,
})
});
}
Run Code Online (Sandbox Code Playgroud)
sam*_*man 15
仅基于此声明:
const state = reactive({
user: {
uid: "",
provider: string[],
}
});
Run Code Online (Sandbox Code Playgroud)
您编写它的目的是为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[],
}
});
Run Code Online (Sandbox Code Playgroud)
然而,当我们看看你如何使用这个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,
})
});
}
Run Code Online (Sandbox Code Playgroud)
在这些行中,您将类型的对象推送到数组{ 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 })[],
}
});
Run Code Online (Sandbox Code Playgroud)
您还可以使用接口来命名该对象形状:
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[],
}
});
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
44918 次 |
最近记录: |