我正在尝试使用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
实例 方法,该方法可以读取 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
内完成。如果是这样的话,我会感到震惊,因为没有包含这样的基本功能......
最佳答案
来自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}`;
};
关于javascript - 使用 tcomb,我是否遗漏了某些内容或者无法定义实例函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38532034/