Reputation: 2532
I have an interface:
export default interface ValidationResult {
valid: boolean
errors?: string[]
}
And a function that returns an object implementing that interface:
static validateTitle(title: string): ValidationResult {
if (title == null || title === '')
return {valid: false, errors: ["Title can't be empty."]}
return {valid: true}
}
But when I try to use the first function inside an other function:
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...
}
I get a TypeScript error:
error TS2322: Type '{}' is not assignable to type 'ValidationResult'.
Property 'valid' is missing in type '{}'.
25 return new Promise((resolve, reject) => { resolve(result) })
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
I tried casting with as ValidationResult
everywhere but without success. What is wrong? I don't understand what TypeScript is complaining about.
Upvotes: 3
Views: 7664
Reputation: 255135
Given your function is already async
you need just to return result;
.
Alternatively you can return new Promise<ValidationResult>
.
Typescript does not infer types for promises yet, and it's a known issue: https://github.com/Microsoft/TypeScript/issues/5254
Upvotes: 5