Search code examples
typescriptloopbackjs

How do I type a model to act like an object in loopback?


I have a loopback model which (in many cases) is represented in a raw json form of itself. e.g.

@model()
class SomeModel extends Entity {
  @property({ type: 'string' })
  id?: string;
}

... in raw json would be

interface IRawSomeModel {id?: string}

Is there any way to get the IRawSomeModel programmatically?

One way I can think of is to combine the two, but it's a lot of extra work having to repeat everything e.g.

export interface IRawSomeModel {id?: string}

@model()
export class SomeModel extends Entity implements IRawSomeModel {
  @property({ type: 'string' })
  id?: string;
}

Ultimately, what I'm looking for is something along the syntax of RawObjectFormOfModel<SomeModel>

The point of all this would to be able to have code like so:

const obj: RawObjectFormOfModel<SomeModel> = {}; // no error about missing class functions
obj.id = "test"

What is the best way to get a raw object type representation of models?


Solution

  • The best way I can find to do this is to create an interface and implement it.

    export interface IRawSomeModel {id?: string}
    
    @model()
    export class SomeModel extends Entity implements IRawSomeModel {
      @property({ type: 'string' })
      id?: string;
    }
    

    I'm hoping I can find a way to take the decorator information and use it to generate the interface.