我有一个界面:
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在抱怨什么。
答案 0 :(得分:4)
鉴于您的功能已经async
,您只需要return result;
。
或者,您可以return new Promise<ValidationResult>
。
Typescript尚不能推断诺言的类型,这是一个已知问题:https://github.com/Microsoft/TypeScript/issues/5254