【问题标题】:Using tcomb, am I missing something or is it not possible to define an instance function?使用 tcomb,我是否遗漏了什么或者无法定义实例函数?
【发布时间】:2023-03-17 16:29:01
【问题描述】:

我正在尝试使用tcomb,但目前失败了,因为我无法理解如何定义实例函数。

假设我有一个类型:

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),
})

到目前为止一切顺利。

问题

现在假设我想添加一个month instance 方法,该方法可以读取this 并获得正确的月份名称:

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

如果我尝试将它添加到上面的内部,它就是看不到它。

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

console.log(b1.month)

如果我尝试执行 mixin 或除了每次都定义函数之外的任何其他操作,也会发生同样的情况。

我最初有 of 语法和下面的函数 compare...

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),
})

还是没有骰子。

我开始认为我想做的事情在tcomb 内是做不到的。如果是这样的话,我会感到震惊的是,没有包括这样的基本能力......

【问题讨论】:

    标签: javascript tcomb


    【解决方案1】:

    来自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}`;
    };
    

    【讨论】:

      猜你喜欢
      • 2010-09-22
      • 2023-02-03
      • 1970-01-01
      • 1970-01-01
      • 2012-03-23
      • 2020-10-20
      • 1970-01-01
      • 2011-09-03
      • 1970-01-01
      相关资源
      最近更新 更多