Flowtype constantly requiring null checks

前端 未结 2 1587
情书的邮戳
情书的邮戳 2021-02-14 00:52

I\'m wondering how to avoid these numerous null checks or at least understand what the point is because it seems counter-productive.

Flowtype is giving me an error for

相关标签:
2条回答
  • 2021-02-14 01:05

    When I know for sure that my variable won't be null and Flow doesn't, I use an unwrap() function:

    export default function unwrap<T>(value: T): $NonMaybeType<T> {
      if (value !== null && value !== undefined) return value
      throw new Error('Unwrapping not possible because the variable is null or undefined!')
    }

    0 讨论(0)
  • 2021-02-14 01:23

    By using a type checker, you are opting into the rules that it enforces. Accessing a property on a nullable type is one of those restrictions. So if you want to have exceptions for null values, you need to explicitly throw to prove to Flow that it is what you want. You could for instance make a module like

    if (!document.body) throw new Error("Unexpectedly missing <body>.");
    export const body: HTMLElement = document.body;
    
    export function querySelector(el: HTMLElement, selector: string): HTMLElement {
        const result = el.querySelector(selector);
        if (!result) throw new Error(`Failed to match: ${selector}`);
        return result;
    }
    

    By throwing, these functions explicitly say "I will return an element" in all cases, and in null cases, they will throw exceptions.

    Then in your normal code, you are guaranteed you can use those

    import {body, querySelector} from "./utils";
    
    body.appendChild(document.createElement('div'));
    
    querySelector(body, 'div').setAttribute('thing', 'value');
    

    and it will typecheck property.

    0 讨论(0)
提交回复
热议问题