繁体   English   中英

你能检查一个对象在运行时是否符合Flow类型吗?

[英]Can you check if an object conforms to a Flow type at runtime?

我有一个正在解析的JSON对象,我正在为输出编写测试,我不能在运行时检查特定对象是否符合流类型。

const object = {/**/}

type SomeType = {
    foo: string,
    bar: bool,
    baz: Object,
}

describe('object', () => {
    describe('.subfield', () => {
        it('conforms to SomeType', () => {
            // Here I want to write an 'expect'
            // that checks if object.subfield
            // conforms to the SomeType flow type?
        })
    });
});

有什么方法可以实现吗?

如果你的意思是在运行时使用 flow,答案肯定是no,flow是用ocaml写的。 祝你好运从JavaScript中调用它。 如果您的意思是验证对象属性的类型,答案大多数情况下是肯定的。 您必须手动检查字段的类型。 我会从这样的事情开始:

let expectedKeys = ['foo', 'bar', 'baz'].sort().toString();
expect(Object.keys(testObj).sort().toString()).toBe(expectedKeys);

确保对象具有正确的密钥。

然后,您必须检查这些键的值的类型是否正确。 对于内置插件,这很容易:

const _extractHiddenClass = (r => a => {
  return Object.prototype.toString.call(a).match(r)[1].toLowerCase();
})(/ ([a-z]+)]$/i);

_extractHiddenClass(/inrst/i); // regexp
_extractHiddenClass(true);     // boolean
_extractHiddenClass(null);     // null

等等。 对于你自己的类型通过构造函数使用new我使用:

const _instanceOf = (ctor, obj) => {
  return (obj instanceof ctor) || 
   (ctor.name && ctor.name === obj.constructor.name);
};

虽然这不是完全万无一失的,但它应该运作得很好。 为了进行一些无耻的自我推销,我写了一个小库来处理很多这类东西,在这里找到它。 也在上午

检查https://codemix.github.io/flow-runtime用于JavaScript的与流兼容的运行时类型系统。

运行时类型项目看起来很有希望。

从README,

example-types.js

// @flow
export type PhoneNumber = string;

export type User = {
  username: string;
  age: number;
  phone: PhoneNumber;
  created: ?Date;
}

validator.js

var types = require('runtime-types')
var validate = require('runtime-types').validate

var MyTypes = types.readFile(path.join(__dirname, '../test/example-types.js'))

var VALIDATORS = {
  PhoneNumber: validate.validateRegex(/^\d{10}$/),
}

var validators = validate.createAll(VALIDATORS, MyTypes)

var errs = validators.User({
  age: 23,
  phone: "8014114399"
})

// ==> [ { key: 'username', value: undefined, error: 'missing' } ]

我不知道为什么人们不再使用它,但是joi是一个很棒的形状和类型验证库

您可以定义任何对象形状,然后只检查哪些对象符合。 如果你想要一个类似体验的断言,你可以这样做

const schema = joi.object().keys({a:joi.string()});
joi.assert(myObj,schema,"error message") 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM