Skip to content

How to inherit? #16

@goswinr

Description

@goswinr

TS can inherit interfaces, F# not.
This can be bypassed by creating a separate module that has classes of the same name:

Generated code from Types.Web :

open Fable.Core

/// All classes in this module are empty.
/// They are only used to allow inheriting from types defined as interface.
/// Use this module when you need to inherit from type that is only defined as an interface.
[<RequireQualifiedAccess>] // don't open this. it would shadow the interfaces
module Inheritable =
    

    /// This is NOT a Browser.Types.HTMLElement !
    /// It is just an empty class with the same name.
    /// It used only for inheriting the Browser.Types.HTMLElement interfaces in F#.
    /// Use like: ' type [<AttachMembers>] MyClass() = inherit Inheritable.HTMLElement()'
    /// Then inside the class you can get the current instance via 'base.this' 
    [<Global>]    
    type HTMLElement() = 

        [<Global>]
        member _.this : Browser.Types.HTMLElement = 
            JsInterop.emitJsExpr () "this" 

In user code a Web Component can be made like this:

open Fable.Core

[<AttachMembers>] 
type MyWebComponent() =
    inherit Inheritable.HTMLElement()     
    let myElem = base.this // typed as Browser.Types.HTMLElement not Inheritable.HTMLElement

this gnerates:

  export class MyWebComponent extends HTMLElement {
      constructor() {
          super();
          const myElem = this;
      }
  }

see REPL

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions