I have identified what I believe to be a bug in Typescript and have submitted it as an issue here. Considering that this might not get resolved quickly, I am reaching out for suggestions. Does anyone know of a better solution or workaround than the one provided in create_1?
Code
type RecursivePartial<T> = {
[P in keyof T]?: RecursivePartial<T[P]>;
};
type State<T> = { value: T };
function create_1<T>(){
let _x: RecursivePartial<State<T>>;
let _y: State<RecursivePartial<T>>;
_x = _y;
}
function create_2<T>(){
/*
*/
let x: RecursivePartial<State<T>>;
let y: State<T>;
/*
Type 'State<T>' is not assignable to type RecursivePartial<State<T>>'.
Types of property 'value' are incompatible.
Type 'T' is not assignable to type RecursivePartial<T>[P]>'.
Type 'T[string]' is not assignable to type 'RecursivePartial<T[P]>'.
*/
x = y;
}
Expected behavior: The expected outcome was that the second example would be valid TypeScript, with State being assignable to RecursivePartial>. This should hold true as any State would essentially be a partial of itself when T remains consistent.
Actual behavior: However, upon testing, I encountered a type error (as shown above). It appears that defining recursive types breaks down when a generic comes into play.
TS Playground link To see the code and type error in action, visit the TS Playground example.