【问题标题】:How to make optional properties to required based on a condition?如何根据条件将可选属性设置为必需?
【发布时间】:2019-08-18 18:48:06
【问题描述】:

这是我的代码:

interface IOptions {
  clientId: string;
  token: string;
}

interface IComponent {
  name: string;

  parent?: { name: string };
}

async function createComponent(opts?: IOptions): Promise<IComponent> {
  const component: IComponent = { name: '' };

  if (opts) {
    component.parent = { name: `${opts.clientId}-${opts.token}` };
  }

  return component;
}

async function main() {
  const { name, parent } = await createComponent();

  console.log(parent.name);
}

如果opts 存在于createComponent 函数中,我想将IComponentIComponent 接口的可选属性设置为必需属性。

目前,当我在main 函数中使用parent.name 时出现错误。

对象可能是'未定义'.ts(2532)

我希望createComponent函数的返回值接口是这样的:如果opts存在则Promise&lt;IComponentRequired&gt;,如果opts不存在则返回Promise&lt;IComponent&gt;。像这样:

interface IComponentRequired {
  name: string;

  parent: { name: string };
}

我的想法是IComponent => Required&lt;T&gt; => IComponentRequired

更新

这是我的尝试,但没有成功。

async function otherMain() {
  const opts: IOptions = { clientId: '123', token: '321' };
  const component: Required<IComponent> = await createComponent(opts);

  console.log(component.parent.name);
}

出现错误:

类型“IComponent”不可分配给类型“必需”。 属性“父级”的类型不兼容。 键入'{名称:字符串; } | undefined' 不可分配给类型 '{ name: string; }'。 类型“未定义”不可分配给类型“{名称:字符串; }'.ts(2322)

【问题讨论】:

标签: typescript


【解决方案1】:

您可以使用重载来返回所需版本或属性可选的版本:

interface IOptions {
    clientId: string;
    token: string;
}

interface IComponent {
    name: string;

    parent?: { name: string };
}

async function createComponent(): Promise<IComponent>
async function createComponent(opts: IOptions): Promise<Required<IComponent>>
async function createComponent(opts?: IOptions): Promise<IComponent> {
    const component: IComponent = { name: '' };

    if (opts) {
        component.parent = { name: `${opts.clientId}-${opts.token}` };
    }

    return component;
}

async function main() {
    const opts: IOptions = { clientId: '123', token: '321' };
    const component: Required<IComponent> = await createComponent(opts);

    console.log(component.parent.name);
}

【讨论】:

  • 谢谢。第二个错误消失了。但是第一个错误仍然存​​在。这似乎是有道理的。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-06-18
  • 2018-05-03
  • 1970-01-01
  • 2018-06-27
  • 2011-10-03
  • 1970-01-01
相关资源
最近更新 更多