FS0008: Indeterminate runtime coercion

This message is given when a type-test pattern is used to match a value, but the cast cannot be safely proven at compile time because the type value has not been determined by the compiler. This often happens when matching on a function parameter whose type has been inferred. The following code illustrates an example of this:

let unboxAndPrint x = 
    match x with
    | :? string as s -> printfn "%s" s
    | _ -> printfn "not a string"

This code results in the following output:

This runtime coercion or type test from type
    'a
to
    string
involves an indeterminate type based on information prior to this program point. Runtime type tests are not allowed on some types. Further type annotations are needed.

In this code, the function parameter x has not had a type inferred for it. This could be for any number of reasons, ranging from the parameter not being used in ways that give the type-inference algorithm any information, to the function not being called anywhere else in the code. Because the type of x has not been inferred, the compiler cannot guarantee that the type of x is able to be cast as a string. Because the compiler cannot guarantee that this cast is able to be performed at runtime, it gives this message.

To fix this message you must provide the compiler more information about the type of the value for which you are using the type-test pattern.

One way of fixing the above code would be to apply a type to the x parameter directly:

let unboxAndPrint (x: obj) = 
    match x with
    | :? string as s -> printfn "%s" s
    | _ -> printfn "not a string"

In this code, the x parameter is given a type of obj, and since obj is able to be type-tested to see if the underlying representation is string, the function now compiles.

Another way of fixing the erroneous code is to use a different way of converting the x parameter to a string:

let unboxAndPrint x = 
    printfn "%s" (string x)

In this code, the use of the string function on the x parameter has given the compiler enough information to infer the type of x as string, so the error is resolved by refactoring the function.