I have an arbitrary structure consisting of nested arrays and objects, with ValidationError objects as leaves. To type this I need a recursive type as shown in Typescript guidelines.
While the assignment (const x = ...) seems to pass the type check, accessing the structure (x.errors.a) gives a TypeScript error which I cannot understand:
Error: TS2339: Property 'a' does not exist on type 'ValidationResultElement'.
Property 'a' does not exist on type 'ValidationResultObject'.
see code on TypeScript Playground
export interface ValidationResult {
errors: ValidationResultElement;
}
type ValidationResultElement =
ValidationResultObject | ValidationResultArray | ValidationError;
interface ValidationResultArray extends Array<ValidationResultElement> {
}
interface ValidationResultObject {
[key: string]: ValidationResultElement;
}
interface ValidationError {
details: string;
}
// This works:
const x: ValidationResult = {
errors: { a: { b: [{ c: { details: 'foo' } }] } }
};
// This produces a type error:
console.log(x.errors.a);
(x.errors as ValidationResultObject).a