Recursive, generic type - type checking
I would like to create a 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 relationships as IOne
, but different value types, for example. boolean
in the 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 can't get it to typescript@2.3.3
work correctly when I need to type-check on related types.
I added a key anything
that is not defined in my datatypes, so I would like typescript to show me the error here. As expected, I see an error at one level deep (inner key two
), but the same key does not throw an error at two levels deep (inside a key three
).
Why? Is there something I can do to achieve this with typescript?
source to share
No one has answered this question yet
Check out similar questions: