如何禁用单行的 Flow (JS) 类型检查

Der*_*ike 14 javascript unit-testing flowtype

我的一些单元测试涉及将无效(错误类型)数据传递给函数。例如:

// user.js

type User = {
    id: number,
    name: string,
    email: string
}

export function validateUser(user: User): Promise<void> {
    return new Promise((resolve, reject) => {
        // resolve if user is valid, reject if not
    })
}
Run Code Online (Sandbox Code Playgroud)
// user.unit.js

import {validateUser} from '../user.js' 

describe('validateUser', () => {
    it('should reject if user is not valid', () => {
        const invalidUser: User = {}
        expect(validateUser(invalidUser)).to.be.rejected
    })
})
Run Code Online (Sandbox Code Playgroud)

由于invalidUser变量不符合User类型,我得到一个流程错误:

Cannot call validateUser with invalidUser bound to user because:
 • property id is missing in object literal [1] but exists in User [2].
 • property name is missing in object literal [1] but exists in User [2].
 • property email is missing in object literal [1] but exists in User [2].
Run Code Online (Sandbox Code Playgroud)

显然我希望这个变量无效,那么如何禁用这个单个实例的流类型检查?

Der*_*ike 20

根据.flowconfig [options] docs,有一个选项可以指定抑制注释。Flow 将检测此注释并忽略以下代码行。

默认情况下:

如果您的配置中未指定抑制注释,则 Flow 将应用一个默认值:// $FlowFixMe.

因此,只需添加注释 ( $FlowFixMe) 即可禁止对单行进行类型检查。

// $FlowFixMe
const invalidUser: User = {}
Run Code Online (Sandbox Code Playgroud)