我正在使用 io-ts 构建一个简单的 record 编解码器:
import * as t from "io-ts";
const myRecordCodec = t.record(t.string, t.string);
我认为这相当于以下类型:
type MyRecord = Record<string, string>;
我测试如下:
describe("myRecordCodec", () => {
it("returns true for record", () => {
expect(myRecordCodec.is({ a: "Oh hai, Mark!" })).toBe(true);
});
it("returns false for date", () => {
const myDate = new Date();
expect(myRecordCodec.is(myDate)).toBe(false);
});
});
我惊讶地发现第二次测试失败了。
这是预期的吗? 我正确使用
record
吗?
record
编解码器需要一个带有字符串键和字符串值的对象。 Date
对象具有字符串键但非字符串值,因此测试应该失败。确保 Date
对象没有被强制或误解。
import * as t from "io-ts";
const myRecordCodec = t.record(t.string, t.string);
const myDate = new Date();
console.log(myRecordCodec.is(myDate)); // Should log false
检查
myDate
是否正在被转换或者是否有任何polyfills影响行为。