'string' 仅指类型,但在这里用作值

'string' only refers to a type, but is being used as a value here

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

创建一个名为 IUser 的界面,然后按如下方式输入您的反应项目:

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

仅基于此声明:

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