首页 > 解决方案 > 如何修复动态布尔变量分配的 FlowJS 错误?

问题描述

//Person Type  
type Person{
    canDisplayButton:boolean,
    anotherEmail:string
}

const canEdit:boolean = person.canDisplayButton && data.anotherEmail;

Flow 抛出一个错误说anotherEmail: string (This type is incompatible with boolean)

如何解决这个问题?

标签: reactjsflowtype

解决方案


您看到的错误正在发生,因为

const canEdit = true && 'text';

// results into

canEdit // 'text'

正如您定义的那样,它canEdit是布尔值 - 为其分配一个字符串 - 会导致错误。所以解决方案是为其分配适当的类型

const canEdit:boolean = person.canDisplayButton && data.anotherEmail !== '';

// or 

const canEdit:boolean = Boolean(person.canDisplayButton && data.anotherEmail);

// or

let canEdit = false;

if (person.canDisplayButton && data.anotherEmail) {
    canEdit = true;
}

推荐阅读