0

I am trying to use tcomb and failing at the moment because I cannot wrap my head around how to define an instance function.

Say I have a type:

t.struct({
  year: t.Integer,
  monthIndex: t.Integer,
  dayIndex: t.maybe(t.Integer),
  indexInMonth: t.maybe(t.Integer),
  title: t.Str,
  subtitle: t.maybe(t.Str),
  description: t.maybe(t.Str),
  iconIdentifier: t.maybe(t.Str),
})

so far so good.

The problem

Now let's say I want to add a month instance method that can read this and get the right month name:

month() {
  return MonthsInYear[this.monthIndex]
},

If I try adding that to the interior of the above, it just doesn't see it.

const b1 = CalEvent({
  year: 2015,
  monthIndex:2,
  title: 'abc',
  description: 'abc'
})

console.log(b1.month)

The same happens if I try to do mixin or really anything other than defining the function every single time.

I originally had the of syntax in there as with the function compare below...

t.struct({
  year: t.Integer,
  monthIndex: t.Integer,
  compare: t.func([CalEvent], CalEventComparisonResult).of(
    (toCompare) => CalEvent(compare(this,toCompare))
  ),
  dayIndex: t.maybe(t.Integer),
  indexInMonth: t.maybe(t.Integer),
  title: t.Str,
  subtitle: t.maybe(t.Str),
  description: t.maybe(t.Str),
  iconIdentifier: t.maybe(t.Str),
})

Still no dice.

I am beginning to think that what I want to do cannot be done within tcomb. And if that is the case I will be shocked that such a basic capability is not included...

tacos_tacos_tacos
  • 10,277
  • 11
  • 73
  • 126

1 Answers1

2

From the README

const Person = t.struct({
  name: t.String,              // required string
  surname: t.maybe(t.String),  // optional string
  age: Integer,                // required integer
  tags: t.list(t.String)       // a list of strings
}, 'Person');

// methods are defined as usual
Person.prototype.getFullName = function () {
  return `${this.name} ${this.surname}`;
};
gcanti
  • 1,462
  • 10
  • 9