【问题标题】:TypeScript define interface for "as X"TypeScript 为“as X”定义接口
【发布时间】:2019-10-11 02:03:16
【问题描述】:

我有以下代码:

const [surveyResponses, totalCount]: [SurveyResponse[], number] =
await this.someRepo.findByFilters(filter) as [SurveyResponse[], number];

是否可以为as [SurveyResponse[], number] 部分提供接口? findByFilters 函数返回或不返回分页结果,所以我想为每个结果提供一个接口。

【问题讨论】:

  • 请注意,您不需要两个 [SurveyResponse[], number] 注释,只需要一个或另一个。
  • 不,findByFilters 要么只返回一个 SurveyResponse 数组,要么返回问题中的数组。 tsc 如果我没有定义它会抛出一个错误。
  • 不,你不需要两者。 as 断言足以定义类型,或者如果它可以分配给带有注释的元组类型,则您不需要断言,但如果不是,您当然不需要 both,只需断言。

标签: typescript types interface typing


【解决方案1】:

不是接口而是类型别名,是的:

type X = [SurveyResponse[], number];

const [surveyResponses, totalCount]: X = ...
await this.someRepo.findByFilters(filter) as X;

【讨论】:

    猜你喜欢
    • 2015-07-27
    • 1970-01-01
    • 2020-11-24
    • 1970-01-01
    • 2019-06-09
    • 2017-07-02
    • 1970-01-01
    • 1970-01-01
    • 2021-06-19
    相关资源
    最近更新 更多