Flowtype constantly requiring null checks

前端 未结 2 1582
情书的邮戳
情书的邮戳 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: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 .");
    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.

提交回复
热议问题