简体   繁体   中英

Translating JS function object with 'this' parameter to Fable

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?

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
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM