Translating JS function object with 'this' parameter to Fable

86 views Asked by At

I have a TypeScript config object that looks something like this:

interface Config {
    renderText?: ((this: {
        name: string;
    }, props: {
        prop1: Prop;
    }) => string) | null;
}

When using ts2fable I get the following automatic translation:

type [<AllowNullLiteral>] Config =
    abstract renderText: ({| name: string |} -> {| prop1: Prop |} -> string) option with get, set

However looking at the usage this doesn't seem correct. The this parameter should be implicitly available somehow.

let config = {
  renderText(props) {
    return this.name
  }
}

What is the correct way to define this interface in F# Fable so that a this parameter is automatically available?

1

There are 1 answers

0
tranquillity On

The correct way to represent this is to define your interface as a method rather than a function property:

type Config =
  abstract renderText: {| prop1: Prop |} -> string

In your implementation you access the jsThis value from Fable.Core:

{ new Config  with
    member this.renderText(props) =
      let this : {| name: string |} = jsThis
      this.name
}