Skip to content

RFC: New GenType for TypeScript #6196

Closed as not planned
Closed as not planned

Description

@cometkim

Proposes a new type of GenType that is incompatible with the existing GenType (will probably have the name GenType v2 or something quite different)

Motivation

GenType is a must in today's JS ecosystem starting with TypeScript. GenType is ending support for JS(untyped) and Flow, which it had previously, and is focusing more on TypeScript.

As ReScript v11 gets better interop capabilities and gets rid of runtime conversions.

It may be a good time to explore new possibilities of GenType through aggressive changes.

Goals

  • Supports only TypeScript.
  • Only emits TypeScript declaration files (.d.ts)
  • 100% compatible with ReScript's build output
  • Remove @genType attribute
  • Remove runtime features (dropping @genType.as, @genType.import support)
  • Much simplified codebase

Design

The key to the change is to assume the output of GenType is no longer the input of tsc. Instead, it becomes the direct output.

The only behavior of the new GenType is to emit an interface per module. So it is not specified per binding, but per project.

%%private(let value = 123)

let foo = () => value

Will generates Module.bs.d.ts next to the Module.bs.js

export const foo: () => number;

So makes Module.bs.js usable in a TypeScript project without any additional builds. That's it. All we have to do is adjust the output to represent the ReScript output.

No attributes

New genType will work for all sources if enabled. It no longer requires a @genType attribute on a per-binding basis, nor does it introduce a per-file attribute like @@genType.

The @genType attribute makes PPX compatibility difficult (#6537) and requires complexity to track dependencies. This is because even if the user does not specify it, it appears implicitly according to the relationship.

Configuration

Don't inherit the existing gentypeconfig. Almost all existing options are not required.

Determine the output format and location via package-specs.

Determine the output filename via suffix. e.g. .bs.js, -> .bs.d.ts.

Shims

Shims for external types are OK. Use it as-is.

If the project is a library, shims must be published together.

Nested / First-clss modules.

Namespaces might be useful for representing nested modules (See #6117). But we don't use namespaces here because it isn't compatible with type referencing and first-class module syntax.

Example: First-class modules
@@genType

module type MT = {
  let x: int
  type t = int
  @module("foo") external f: int => int = "f"
  module type XXX = {
    type tt = string
  }
  module EmptyInnerModule: {

  }
  module InnerModule2: {
    let k: t
  }
  module InnerModule3: {
    type inner = int
    let k3: inner => inner
  }
  module type TT = {
    let u: (int, int)
  }
  module Z: TT
  let y: string
}

module M = {
  let y = "abc"
  module type XXX = {
    type tt = string
  }
  module EmptyInnerModule = {

  }
  module InnerModule2 = {
    let k = 4242
  }
  module InnerModule3 = {
    type inner = int
    let k3 = x => x + 1
  }

  module type TT = {
    let u: (int, int)
  }
  module Z = {
    let u = (0, 0)
  }
  type t = int
  @module("foo") external f: int => int = "f"
  let x = 42
}

type firstClassModule = module(MT)

let firstClassModule: firstClassModule = module(M)

will generates

export type MT = {
  x: number,
  t: number,
  XXX: MT_XXX,
  EmptyInnerModule: MT_EmptyInnerModule,
  InnerModule2: MT_InnerModule2,
  InnerModule3: MT_InnerModule3,
  TT: MT_TT,
  Z: MT_Z,
};

type MT_XXX = {
  tt: string,
};

type MT_EmptyInnerModule = {
};

type MT_InnerModule2 = {
  k: MT["t"],
};

type MT_InnerModule3 = {
  inner: number,
  k3: (arg1: MT_InnerModule3["inner"]) => MT_InnerModule3["inner"],
};

type MT_TT = {
  u: [number, number],
};

type MT_Z = MT_TT;

export const M: {
  x: number,
  t: number,
  XXX: M_XXX,
  EmptyInnerModule: M_EmptyInnerModule,
  InnerModule2: M_InnerModule2,
  InnerModule3: M_InnerModule3,
  TT: M_TT,
  Z: M_Z,
};

type M_XXX = {
  tt: string,
};

type M_EmptyInnerModule = {
};

type M_InnerModule2 = {
  k: M["t"],
};

type M_InnerModule3 = {
  inner: number,
  k3: (arg1: M_InnerModule3["inner"]) => M_InnerModule3["inner"],
};

type M_TT = {
  u: [number, number],
};

type M_Z = M_TT;

export type firstClassModule = MT;

export const firstClassModule: firstClassModule;

Opaque types

TBD

GADT

TBD

Others

Please leave comments what cases it needs to cover.

Activity

  1. cristianoc commented on Apr 24, 2023

    @cristianoc
    Collaborator

    Would you update some info which is old? As of master, gentype does not generate any runtime conversion so we can get that out of the design considerations.

  2. cristianoc commented on Apr 24, 2023

    @cristianoc
    Collaborator

    I would include removing shims as a goal. Do we need them?

  3. cristianoc commented on Apr 24, 2023

    @cristianoc
    Collaborator

    Based on this goal #6210, it seems sensible to only focus on export to JS, and move imports questions to the FFI layer, which can be revisited separately. So effectively, the concept of @genType.import could be removed.

    In particular, typed checked bindings could be re-explored in the context of #6211

    Import: a bit more clarity is needed. It would be nice to remove them. Does it mean that imports will be essentially untyped? Or that it is not genType's job to make sure that imports are well typed?
    Not sure which one is meant, just asking for clarification of the proposal.

  4. cristianoc commented on Apr 24, 2023

    @cristianoc
    Collaborator

    Not sure we need a new tool. It seems easier to just add configuration to turn on the new mode. And if successful, the new mode will replace the legacy mode over time which will be deprecated and removed.

  5. added this to the v12 milestone on Apr 26, 2023
  6. gustavopch commented on Nov 19, 2023

    @gustavopch

    Having GenType generate .bs.d.ts automatically will be very much appreciated. While that doesn't happen, I'm using this js-post-build script in case it helps anyone:

    #!/usr/bin/env bash
    
    bs_js_path="$1"
    bs_ts_path="${bs_js_path/bs\.js/bs.ts}"
    bs_dts_path="${bs_js_path/bs\.js/bs.d.ts}"
    gen_tsx_path="${bs_js_path/bs\.js/gen.tsx}"
    
    if [ -f "$gen_tsx_path" ]; then
      mv -f "$gen_tsx_path" "$bs_ts_path"
      yarn tsc --declaration --emitDeclarationOnly --isolatedModules --skipLibCheck "$(readlink -f "$gen_tsx_path")"
      rm -f "$bs_ts_path"
    else
      rm -f "$bs_ts_path" "$bs_dts_path" "$gen_tsx_path"
    fi
  7. cometkim commented on Dec 14, 2023

    @cometkim
    MemberAuthor

    I would include removing shims as a goal. Do we need them?

    This is possible if we embed .d.ts for things that are treated first-class like Js/React/Belt, etc.

  8. changed the title [-]Draft RFC: New GenType for TypeScript[/-] [+]RFC: New GenType for TypeScript[/+] on Jan 25, 2024
  9. cometkim commented on May 26, 2024

    @cometkim
    MemberAuthor

    Retreat Update: GenType

    We (@cometkim, @JonoPrest, @cristianoc) discussed the roadmap and detailed design of the output formats in the ReScript Retreat 2024. And we have concluded most issues! If there are no remaining questions, implementation will begin as soon as possible.

    Core concepts

    Most are similar to existing plans but are more specific.

    Drop attributes

    Except in special cases, all @genType attributes will be ignored. Instead, enabling genType in the project will generate a type that matches any actual JavaScript value.

    Not only is this clearer, but it also significantly reduces the complexity of the compiler codebase.

    Drop shims

    We haven't found a legitimate use case for shims without runtimes.

    By supporting .d.ts, libraries can ship type definitions without any additional TypeScript toolchain. Alternatively, it can also be generated on the fly by the user.

    Also many cases may covered by using @genType.import

    Keeping support @genType.import

    We found that @genType.import has actual use case unlike other attributes.

    @genType.import(("./modulePath", "TypeName"))
    type typeName = {
      ...
    };

    This serves to connect back to external types in GenType output while using compatible types defined in ReScript. In other words, it's like FFI but for TypeScript types.

    There was suggestion for syntax support rather than atrribute,

    @module("./modulePath") @type
    external typeName: resType = "TypeName"

    but that won't happen right away because it doesn't solve extra problem and adds complexity somehow.

    New opaque format

    We're removing special attributes like @genType.opaque but still support opaque types.

    We explored practical use cases leveraging opaque types in both ReScript and TypeScript worlds, and designed interoperable formats. An example:

    type valid
    type invalid
    
    type t<'s> = string
    
    let validate: t<invalid> => t<valid>

    This pattern is well known as a "phantom types" in many other type systems and as a "branded types" in TypeScript.

    The existing format uses TypeScript’s abstract classes and protected fields to express .

    abstract class valid { protected opaque!: any }
    abstract class invalid { protected oapque!: any }
    abstract class t<a> { protected oapque!: a }

    This is a well-known trick, but since class has both value and type semantics, there is a possibility that identifier may be abused in any value position. It can be triggered by IDE auto-completion even if the user doesn't intend it to be.

    The new proposed format is:

    declare global {
      interface $$Module {
        const valid: unique symbol;
        const invalid: unique symbol;
        const t: unique symbol;
      }
    }
    
    export type valid = { [$$Module.valid]: [] };
    export type invalid = { [$$Module.invalid]: [] };
    export type t<a> = string & { [$$Module.t]: [a] };

    It could look more complex but gives the best usability so far.

    • Use unique symbols to protect values from being randomly instantiated from outside.
    • Minimizes the exposure of value semantics connected to exports. The only part is the unique symbol but hidden as an internal interface.
    • Register internal interfaces in the global namespace to avoid unintentional auto-imports.

    One downside is TS error message will be bloated (even) more. But it doesn't make much of a difference from utilities (e.g. ts-brand) that are popular today.

    Fix GADT format

    GADT doesn't work today, but it's easy to fix.

    GADT types have different names for each specific type by appending $Tag

    type rec t<_> =
      | Int(int): t<int>
      | Float(float): t<float>
    
    let logInt: t<int> => unit = v => {
      switch v {
      | Int(v) => Js.log(v)
      }
    }
    
    let logFloat: t<float> => unit = v => {
      switch v {
      | Float(v) => Js.log(v)
      }
    }
    
    let log: type a. t<a> => unit = v => {
      switch v {
      | Int(_) => logInt(v)
      | Float(_) => logFloat(v)
      }
    }

    will generates

    export type t$Int = { TAG: "Int"; _0: number };
    export type t$Float = { TAG: "Float"; _0: number };
    export type t = (
      | t$Int
      | t$Float
    );
    
    export const logInt: (v: t$Int) => void;
    
    export const logFloat: (v: t$Float) => void;
    
    export const log: (v: t) => void;

    This format may not work for all parameterized GADTs, but at least it supports the most common and practical GADT use case.

    Modules format

    (Note: This part was left out of the Retreat discussions, but I proposed again as a result of the further PoC)

    Because ReScript modules can contain both values and types and module types can be converted to first-class module values anytime. Therefore, we need to represent module values and types in a more flexible way.

    To make this as simple as possible, I've suggested a few rules.

    1. Modules (types) always produce a pair of value representation and type representation.
    2. A value representation doesn't contain any type fields, but a type representation is defined as a superset containing both value fields and type fields.
    3. Value representations reference only other value representations, type representations reference only other type representations
    4. First-class modules use value representation.

    This approach allows us to cover first-class modules while at the same time implementing GenType in a much simpler way. Using these rules, GenType only needs to convert the name in a location without any complex dependency analysis.

    See the example for more details.

    Note: We don't generate it for module functions that are only used in ReScript. Although the TypeScript representation for module functions is not complex, there are no practical use cases.

    Implementation plan

    Phase 1. Tweak the existing implementation

    Add a configuration flag to create .d.ts by tweaking the current GenType implementation.

    Except that original outputs have runtime bindings, this proposal can be treated as a "bug fix" even in existing formats.

    Phase 2. Create a new GenType entry point as an isolated module

    The new implementation is expected to be much simpler than the existing one, so we may eventually have a lighter-weight dedicated implementation.

    Rather, if Phase 1 consumes more time, we can skip it and reimplement the gen.ts(x) output and .d.ts output from scratch.

    Expected migration story

    Typically the only migration task we require of our users is to change the existing .gen.ts(x) import path to the regular .res.js path. Then TypeScript can automatically find definitions from sibling .d.ts.

    Users depend on any shims and need to migrate code a bit. But in most cases we expect that to be the core library. Then removing shims and users don't need extra work.

    And most existing attributes will be ignored. We end up helping the user remove unnecessary attributes in the formatter or another codemod tool.

    Key phrase

    • ReScript: The sensible TypeScript build tool you might look for

    If you have any ideas for it, please comment!

  10. JonoPrest commented on May 27, 2024

    @JonoPrest
    Contributor

    I still feel it would be useful to have @genType.as("...") attribute as well. It's helpful in that you can have idiomatic type names in both ReScript and TypeScript. For instance I use this to uppercase type names in TS but lowercase in Res. It's also helpful for reserved keywords etc.

  11. cometkim commented on May 27, 2024

    @cometkim
    MemberAuthor

    Ok, that makes sense. IMO, just @as should be fine. In the end, GenType needs to minimize having special grammar and to work well within regular ReScript codebase without any modification

  12. cometkim commented on Aug 20, 2024

    @cometkim
    MemberAuthor

    @genType.import would have a special form to assert type-safety

    See #6947 (comment)

  13. gabriel-bezerra commented on Aug 21, 2024

    @gabriel-bezerra

    @cometkim, if you are interested in use cases for the new design, I'm trying to use genType.import for for type safety in bindings and am missing the ability to use it with JS classes.

    TS side

    export class C {
      constructor(x: boolean) {};
      method() { console.log(this.x) };
      static staticFunction(x: number) { return [new C(true), false]; };
    }
    
    export function moduleFunction(x: number, y: boolean): string { return `${x}${y}`; };

    Res side

    [@genType.import ("package", "C")]
    type c;
    
    // this works
    [@genType.import ("package", "moduleFunction")]
    external module_function_here: (int, bool) => string = "module_function_here";
    
    // these don't work
    [@genType.import] [@bs.new]
    external constructor_here: bool => c = "constructor_here";
    
    [@genType.import] [@bs.send]
    external method_here: c => unit = "method_here";
    
    [@genType.import ("package", "C.staticFunction")]
    external static_here: int => (c, bool) = "static_here";
  14. jmagaram commented on Nov 11, 2024

    @jmagaram
    Contributor

    Overall very excited about the possibility of new and simpler approach here. In particular I have had difficulty using GenType with functors and include, which are the best way to wrap basic int and string types into domain-specific types with validation, construction, equality, ordering, and serialization functionality.

    Please see #7156

  15. moved this to Todo in RFCson Nov 28, 2024
  16. removed this from the v12 milestone on May 5, 2025
  17. cometkim commented on May 14, 2025

    @cometkim
    MemberAuthor

    I'm sorry for the lack of progress on Gentype. Gentype is still a top priority feature, but I'm terrible at prioritizing on OSS.

    The compiler codebase is approaching my threshold of acceptable code complexity, forcing me to take yet another refactoring task.

    I've evaluated the Gentype codebase several times and decided it's better to rewrite it. However, in the PoC, I had to reinvent most of its complexities.

    The only reason it's complex is due to historical reasons. It has architectural limitations because it was a third-party tool. It is now provided within the compiler but is still poorly integrated.

    Currently, Gentype works through the following process:

    1. Load project configuration
    2. Load & parse *.cmt files to restore typed tree
    3. Process & analyze typed tree
    4. Emit formatted *.ts files

    1-3 here are redundant tasks.

    Ideally, most of the logic could be reused since the compiler already did the same. But it's currently impossible because the compiler discards all type information when it enters the backend process (Lambda IR).

    To improve this situation, @cristianoc and I discussed retaining pointers to type information in the Lambda IR.

    Implementing type-related formats will become simple simply by passing the type information through. We can "upgrade" the existing JavaScript IR to allow adding type information to JSDoc comments, emitting additional .d.ts, or even changing the entire output to TypeScript.

    This approach requires a large-scale change to the Lambda IR. But the changes don't touch the existing backend mechanism, I expect a quick PoC to be possible.

  18. github-actions commented on May 10, 2026

    @github-actions

    This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. Thank you for your contributions.

  19. added
    stale
    on May 10, 2026
  20. moved this from Todo to Done in RFCson May 17, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

stale

Type

No type

Projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions