【问题标题】:Is there a way to force a type in Typescript?有没有办法在 Typescript 中强制输入类型?
【发布时间】:2022-01-06 04:04:22
【问题描述】:

我有这个:

      const res: any = await table.find({}).toArray();
      const data: Type[] = res;

有没有办法做这样的事情:

      const res: Type[] = await table.find({}).toArray();

没有错误:Type 'Document[]' is not assignable to type 'Type[]'. ?

【问题讨论】:

  • 我认为你应该使用filter 来做到这一点。

标签: typescript mongoose types


【解决方案1】:

查看Type Guards and Differentiating Types

如果您确定res 始终是Type 的数组,您可以使用as 强制输入:

const res = await table.find({}).toArray() as Type[]; // res: Type[] now

【讨论】:

    猜你喜欢
    • 2020-06-10
    • 2010-10-13
    • 1970-01-01
    • 2017-08-05
    • 2018-07-21
    • 1970-01-01
    • 1970-01-01
    • 2020-04-08
    • 2013-11-19
    相关资源
    最近更新 更多