Reputation: 2144
Suppose I have the following types:
type TypeA = { A: string }
type TypeB = { B: string }
and I have a union type for them both:
type MyUnionType = TypeA | TypeB
With a type just to contain the union type:
type MyContainer = { Union: MyUnionType }
now if I create an instance of one of the types in the union type:
let resultA = { A = "abc" }
when I try to assign that instance to the value in the container
let result = { Union = resultA }
the compiler complains, saying
Compilation error (line 10, col 24): This expression was expected to have type MyUnionType but here has type TypeA
but TypeA
is one of the valid types specified in the union! How can I assign it to my Union property?
Here is an example of the program: https://dotnetfiddle.net/fgJKpM
Upvotes: 1
Views: 269
Reputation: 144126
In type MyUnionType = TypeA | TypeB
, TypeA
and TypeB
do not refer to the previous TypeA
and TypeB
records, but are nullary constructors for the MyUnionType
type. If you want them to contain values of those types you need to include them in the definition e.g.
type MyUnionType = TypeA of TypeA | TypeB of TypeB
You might want to rename the constructors to avoid confusion between them and the contained types.
you then need to supply the corresponding instance to the constructor:
let resultA = TypeA { A = "abc" }
Upvotes: 6