如何访问 Record<string,unknown> 类型变量的属性?

问题描述

我正在使用 Typescript、nuxt/auth 和 nuxt/axios 开发 Nuxt.js 项目。我正在为我的 API 服务创建某种存储库。我有从后端收到的数据的 DTO。 我有一个 UserDTO,它具有成功登录后 API 发送的回复的确切模式,并且它有一个字段“id”。我想读取属性 Vue.$auth.user.id 并将其作为 get 参数传递。目前我无法更改后端的逻辑以使其仅根据我的令牌做出响应。 下面显示了我的问题所在。

我希望我的 this._user 是声明“id”属性的 UserDTO 类型。但是 $auth.user一个返回 Record<string,unkNown> 的 getter,它在编译时没有任何属性“id”。

export class ServiceRepository{

  _api:ApiService;
  _vue:Vue;
  _user:UserDto | null;

  constructor(vue:Vue) {
    this._api = new ApiService(vue.$axios);
    this._vue = vue;
    this._user = vue.$auth.user;
  }

  // get userId(){
  //   let user = this._user as UserDto
  //   return this._vue.$auth.user.id;
  // }  

  async getUserPets() {
    const { data } = await this._api.query<PetDto>("pets",{ params: { ownerId: this._user.id } });
    return data;
  }


我该怎么办?

更新

我像下面那样改变它并解决了问题,但我对我这样做的方式不满意

  _api:ApiService;
  _vue:Vue;
  _user:Record<string,unkNown> | null;

  constructor(vue:Vue) {
    this._api = new ApiService(vue.$axios);
    this._vue = vue;
    this._user = vue.$auth.user;
  }

  get userId():number|undefined{
    if (this._user !==null)
    {
      return this._user.id as number;
    }
  }  

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...