Recursive, generic type - deep type check

Viewed 319

I would like to create recursive, generic type TRecursive based on my data interfaces IOne, ITwo and IThree that are related as shown below.

The result type TRecursive<IOne> should have similar relations as IOne but different value types, e.g. boolean in example below.

interface IOne {
    pk: number;
    name: string;
    two: ITwo;
}

interface ITwo {
    pk: number;
    name: string;
    three: IThree;
}

interface IThree {
    pk: number;
    name: string;
}

type TRecursive<T> = {
    [P in keyof T]?: TRecursive<T[P]> | boolean;
};

const test: TRecursive<IOne> = {
    pk: true,
    name: true,
    two: {
        pk: true,
        name: true,
        anything: true,        // type error as expected
        three: {
            pk: true,
            name: true,
            anything: true     // no error - why?
        }
    }
};

The thing is I cannot make typescript@2.3.3 to work properly when I need type-check down in related types.

I added key anything that is not defined in my data types, so I would like typescript to show me the error here. As expected I see error in one level deep (inside key two), but the same key does not trigger error two levels deep (inside key three).

Why is that? Is there anything that I can do to achieve this with typescript?

1 Answers

This is pretty common with TS. It stops at the first error before even continuing to look for the next ones.

const test: TRecursive<IOne> = {
    pk  : true,
    name: true,
    two : {
        pk   : true,
        name : true,
        // anything: true,
        three: {
            pk      : true,
            name    : true,
            anything: true, // error
        },
    },
}
Related