【问题标题】:How to fix FlowJS error for dynamic Boolean variable assignments?如何修复动态布尔变量分配的 FlowJS 错误?
【发布时间】:2019-02-01 18:42:32
【问题描述】:
//Person Type  
type Person{
    canDisplayButton:boolean,
    anotherEmail:string
}

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

Flow 抛出错误,提示 anotherEmail: string (This type is incompatible with boolean)

如何解决这个问题?

【问题讨论】:

  • 如果要判断是否定义了data.anotherEmail,能不能不用!!data.anotherEmail判断变量的真实性?
  • 是的,!! 工作。使用Boolean() 也有效。
  • 在这种情况下,我已将其更改为答案 - 请@titogeo 将其标记为正确?
  • 感谢 titogeo,非常感谢!

标签: reactjs flowtype


【解决方案1】:

如果您要确定是否定义了data.anotherEmail,是否可以不使用!!data.anotherEmail 来确定变量的真实性?

【讨论】:

  • 或者更明确地说,Boolean(data.anotherEmail)
【解决方案2】:

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

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;
}

【讨论】:

  • 也可以是undefined,对吗?我还有更多的领域需要评估。我正在寻找是否有flow解决方案?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-09-21
  • 2019-12-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多