Scott Nimrod
Scott Nimrod

Reputation: 11595

How do I assign a type to a union case from a Discriminated Union case?

How do I assign a type to a union case from a Discriminated Union case?

Code:

type ValidationResult<'Result> =
    | Success of 'Result
    | Failure of 'Result

type ValidationError =
    | Error1 of Failure
    | Error2 of Failure

Error:

The type 'Failure' is not defined

Upvotes: 0

Views: 87

Answers (2)

Alexey Romanov
Alexey Romanov

Reputation: 170713

You can't: Failure is not a type. It is compiled to a .NET class, but you can't access this class from F#, it's just an implementation detail.

The normal workaround is to make an actual type corresponding to the case. In your case, it would be

type Failure<'Result> = 'Result

type ValidationResult<'Result> =
    | Success of 'Result
    | Failure of Failure<'Result>

type ValidationError =
    | Error1 of Failure<???>
    | Error2 of Failure<???>

Upvotes: 2

scrwtp
scrwtp

Reputation: 13577

You can't do that. Discriminated union cases aren't types in their own right - think of them as constructors that return values of the DU type. So in your case both Success and Failure are ways to create a ValidationResult<'a>.

Therefore you'd need to do something like this, and it clearly doesn't make much sense:

type ValidationError<'a> =
    | Error1 of ValidationResult<'a>
    | Error2 of ValidationResult<'a>

This might be closer to what you're trying to do:

type ValidationError =
    | Error1
    | Error2

type ValidationResult<'Result> =
    | Success of 'Result
    | Failure of 'Result * ValidationError

Upvotes: 7

Related Questions