core icon indicating copy to clipboard operation
core copied to clipboard

Generic type constructor constraint - the constructor is not found in JavaScript compilation

Open atadi96 opened this issue 7 years ago • 1 comments

I think the following code is correct in F#, but WebSharper can't compile it.

[<JavaScript>]
module HelloWorld =
    type MyType<'A when 'A : (new : unit -> 'A)>() =
        let a = new 'A() //Method name not found in JavaScript compilation: (CreateInstance<_> : unit -> 'T0)
        member __.Text = ""

P.S: I first tried to post this on the forums, but I got an error code 500 from accounts.websharper.com when trying to log in with my github account.

atadi96 avatar Feb 22 '18 22:02 atadi96

This is correct F#, but WebSharper can't translate it at the moment for a reason:

Generics are erased in WebSharper translation, so where translation would depend on the generic type can't be compiled safely. There are some loose handling of this in some cases: equality and comparisons, string an numeric conversions default to a dynamic implementation if used with an unresolved type parameter. But as WebSharper is not tracking metadata and type information at runtime, there is no safe way to translate new 'A() as for a type a parameterless constructor can be renamed or inlined, even if the type parameter would be passed at runtime.

It would be possible to support this (and also Activator.CreateInstance) but it is a non-trivial change in the runtime.

Jand42 avatar Feb 23 '18 09:02 Jand42