【问题标题】:'string' only refers to a type, but is being used as a value here'string' 仅指一种类型,但在此处用作值
【发布时间】:2021-08-23 01:47:57
【问题描述】:

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

【问题讨论】:

  • 正如错误所说...不知道有什么要解释的

标签: typescript firebase vue.js vuejs3 vue-composition-api


【解决方案1】:

仅基于此声明:

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

【讨论】:

    【解决方案2】:

    创建一个名为IUser 的界面,然后键入您的反应项,如下所示:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-08-07
      • 2020-04-28
      • 2020-12-05
      • 2018-03-31
      • 1970-01-01
      • 2023-04-03
      • 2023-04-05
      • 1970-01-01
      相关资源
      最近更新 更多