代码之家  ›  专栏  ›  技术社区  ›  vmarquet njlaboratory

TypeScript:错误TS2322:类型{}不能分配给类型“…”

  •  1
  • vmarquet njlaboratory  · 技术社区  · 7 年前

    我有一个接口:

    export default interface ValidationResult {
      valid: boolean
      errors?: string[]
    }
    

    以及返回实现该接口的对象的函数:

      static validateTitle(title: string): ValidationResult {
        if (title == null || title === '')
          return {valid: false, errors: ["Title can't be empty."]}
    
        return {valid: true}
      }
    

    但当我试图在另一个函数中使用第一个函数时:

    static async validateMovie(title: string): Promise<ValidationResult> {
        const result = this.validateTitle(title)
        if (result.valid === false)
          return new Promise((resolve, reject) => { resolve(result) })
        // other validations...
    }
    

    我收到一个TypeScript错误:

    error TS2322: Type '{}' is not assignable to type 'ValidationResult'.
      Property 'valid' is missing in type '{}'.
    
    25       return new Promise((resolve, reject) => { resolve(result) })
             ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    

    我试着用 as ValidationResult 到处都是但没有成功。怎么了?我不明白TypeScript在抱怨什么。

    1 回复  |  直到 7 年前
        1
  •  5
  •   zerkms    7 年前

    因为你的功能已经 async 你只需要 return result; .

    或者你可以 return new Promise<ValidationResult> .

    Typescript还不能推断承诺的类型,这是一个已知的问题: https://github.com/Microsoft/TypeScript/issues/5254

    推荐文章