Seeking assistance from a TypeScript expert to guide me in implementing monadic behavior. My goal is to develop basic monadic functions like map
and flatMap
for a data type that can have four distinct forms.
I've encountered challenges making the TypeScript compiler accept my types, despite trying various approaches such as classes, abstract classes, and simple types. The following code represents my best attempt so far:
/* Code block with Data namespace */
The current implementation seems incomplete due to TypeScript raising objections to the map function.
While inspecting variables a
, b
, c
, and d
, no issues are found. However, when applied to an array of Data types, the error message appears:
Error: Argument of type 'Data<string, any>' is not assignable to parameter of type 'Initial<string, any>'.
Type 'Loaded<string, any>' is not assignable to type 'Initial<string, any>'.
Types of property 'kind' are incompatible.
Type '"loaded"' is not assignable to type '"initial"'.ts(2345)
The challenge lies in understanding why the TypeScript compiler is struggling with the types. Shouldn't Data<T,E>
perfectly fit the requirements? Why does it attempt to align the argument type across all possible overloads?
If the specific subtypes signatures are removed, leaving only the most generic one, the complaints cease however, this results in loosening the strict typing. Any subtype becomes coerced into its less restrictive type Data<T,E>
, which goes against the desired precision.