【问题标题】:No Overload Matches this call with Vue 3 ref<T>无重载将此调用与 Vue 3 ref<T> 匹配
【发布时间】:2022-01-14 20:14:16
【问题描述】:

我定义了以下类型,我正在尝试与 ref 一起使用,并且最初不想定义所有道具默认值,但我是 TS 错误:No Overload Matches this call强>

interface EmailReminder {
  bcc_emails: string[] | null;
  cc_emails: string[];
  from_email: string;
  message: string;
  offset_days: number;
  subject: string;
  to_emails: string[];
  sent_at: string | Date;
  uuid: string;
}

当我尝试使用 Vue 3 ref 创建反应变量时,通过传递我的类型代替泛型,打字稿会生气并引发以下错误。

const reminder = ref<EmailReminder>({
      to_emails: [],
      cc_emails: [],
      message: '',
      subject: '',
    });

谁能告诉我我在这里做错了什么,我不想让某些属性成为可选的,并且事件不想使用as 来删除它们。

【问题讨论】:

  • 您必须将它们设为可选,否则它们的类型不同。

标签: typescript vue.js vuejs3


【解决方案1】:

它们不是同一种类型,您在这里违背了打字稿的目的。如果您不希望对对象进行严格的类型定义,也许只需坚持使用 javascript。您尝试在这里分配 2 种不同的类型是编译器会选择的。

缺少的必须是可选的,否则无论如何您都会收到此错误。

interface EmailReminder {
  cc_emails: string[];
  message: string;
  to_emails: string[];
  subject: string;
  bcc_emails?: string[] | null;
  from_email?: string;
  offset_days?: number;
  sent_at?: string | Date;
  uuid?: string;
}

或者,您可以将其他值初始化为未定义

const reminder = ref<EmailReminder>({
      to_emails: [],
      cc_emails: [],
      message: '',
      subject: '',
      bcc_emails: undefined
      from_email: undefined;
      offset_days: undefined;
      sent_at: undefined;
      uuid: undefined;
    });

如果您真的不想执行上述操作,我想您可以在技术上创建 2 种类型并允许它成为任一类型

interface BaseEmailReminder {
  cc_emails: string[];
  message: string;
  to_emails: string[];
  subject: string;
}

interface ExtendedEmailReminder extends BaseEmailReminder {
  bcc_emails: string[] | null;
  from_email: string;
  offset_days: number;
  sent_at: string | Date;
  uuid: string;
}

然后去

const reminder = ref<BaseEmailReminder | ExtendedEmailReminder>({
      to_emails: [],
      cc_emails: [],
      message: '',
      subject: '',
    });

我建议与可选成员一起使用,因为第二个示例是一种反模式黑客,并没有真正正确地遵循打字稿行为,并且不是最佳实践,因为没有让这些成员说它们是可选的。

【讨论】:

    猜你喜欢
    • 2020-09-08
    • 2021-08-15
    • 2021-04-21
    • 1970-01-01
    • 2021-10-17
    • 2021-02-04
    • 1970-01-01
    • 2021-12-26
    • 1970-01-01
    相关资源
    最近更新 更多