最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to disable Flow (JS) type checking for a single line - Stack Overflow

programmeradmin4浏览0评论

Some of my unit tests involve passing invalid (improperly typed) data to a function. For example:

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

Since the invalidUser variable does not conform to the User type, I get a flow error:

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].

Obviously I want this variable to be invalid, so how can I disable flow type checking for this single instance?

Some of my unit tests involve passing invalid (improperly typed) data to a function. For example:

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

Since the invalidUser variable does not conform to the User type, I get a flow error:

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].

Obviously I want this variable to be invalid, so how can I disable flow type checking for this single instance?

Share Improve this question asked Apr 8, 2019 at 22:49 Derek SoikeDerek Soike 11.7k3 gold badges82 silver badges76 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 23

According to the .flowconfig [options] docs, there is an option to specify a suppress comment. Flow will detect this comment and ignore the following line of code.

By default:

If no suppression comments are specified in your config, Flow will apply one default: // $FlowFixMe.

So just add a comment ($FlowFixMe) to suppress type checking for a single line.

// $FlowFixMe
const invalidUser: User = {}
发布评论

评论列表(0)

  1. 暂无评论