Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating Generic Types via Type Providers

Is it possible to create a generic type via type providers so that

[<TypeProvider>]
type SampleTypeProvider(config: TypeProviderConfig) as this = 

...
//the below would be the generated type
type A<'b> () = 
     member this.C() : 'b = ...
     member this.D() : 'b = ...
//
...
[<assembly:TypeProviderAssembly>] 
do()
  ....

so that in the usage scenario would look something to

#r @".\bin\Debug\SampleTypeProvider.dll"
type A = SampleTypeProvider.A
type intA = A<int>
type strA = A<str>

And if that is possible - How can I approach it.

like image 580
robkuz Avatar asked Oct 26 '16 14:10

robkuz


People also ask

How do I create a generic type in TypeScript?

Assigning Generic ParametersBy passing in the type with the <number> code, you are explicitly letting TypeScript know that you want the generic type parameter T of the identity function to be of type number . This will enforce the number type as the argument and the return value.

How do you define generic type?

Definition: “A generic type is a generic class or interface that is parameterized over types.” Essentially, generic types allow you to write a general, generic class (or method) that works with different types, allowing for code re-use.

Does TypeScript have generics?

Generics allow creating 'type variables' which can be used to create classes, functions & type aliases that don't need to explicitly define the types that they use. Generics makes it easier to write reusable code.


1 Answers

This is not possible using standard methods. I tried looking around, but could not find a canonical reference, but it is a known limitation and there have been various suggestions to lift the restriction.

Ross McKinlay has a somewhat extreme project called Mixin type provider that works around this by actually generating a file with F# source code when type provider is run (and you can then include this file in your project). This is perhaps more code-generation than type provider, but his talk about the topic is also a good explanation of some of the limitations.

How to address this very much depends on the purpose of the type provider. If you only need limited number of types, you could use something like static parameters and write A<"int"> or A<"string">. You could also mix ordinary non-provided generic types with non-generic provided types (in some clever way). But I think you need to write more about your concrete use case to get a better answer.

like image 183
Tomas Petricek Avatar answered Oct 01 '22 07:10

Tomas Petricek