'string'仅引用类型,但在此处用作值



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,
})
});
}

基于以下语句:

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[], 
}
});

创建一个名为IUser的接口,然后按如下方式键入反应项目:

interface IUser {
user: {
uid: string;
provider: string[];
};

const state = reactive<IUser>({
user: {
uid: '',
provider: [],
},
});

最新更新