Search code examples
javascripttypescriptfeature-detection

Typescript feature detection without creating errors


I'm trying to implement feature detection in a typescript function, but I keep getting linting errors.

It is obvious why I get them, because in some of the cases I'm checking against, the feature doesn't exist in the typescript definition. For example in the function below, I get a typescript error on "doc.body.createTextRange".

public searchContent(text:string) {
    let doc = document;
    let range:any; 
    let selection: any;

    if (doc.body.createTextRange) {
        range = document.body.createTextRange();
        range.moveToElementText(text);
        range.select();
    } else if (window.getSelection) {
        selection = window.getSelection();
        range = document.createRange();
        range.selectNodeContents(text);
        selection.removeAllRanges();
        selection.addRange(range);
    }
}

(By the way, the code can be used for selecting text, see Selecting text in an element (akin to highlighting with your mouse))

What would be the best strategy to avoid these errors? I could extend the body definition with all possible cases, but that seems a bad idea... I can off course switch of linting in this case, but again seems like not a good solution.


Solution

  • You simply typecast to any to force it to accept anything. Also in this particular code, you should check for the standards way of doing it and then fallback to the IE specific one.

    function hl(element: HTMLElement) {
      let doc = document;
      if (!element)
         return;
      if (window.getSelection) {
         let selection = window.getSelection();
         let range = document.createRange();
         range.selectNodeContents(element);
         selection.removeAllRanges();
         selection.addRange(range);
         return;
      }
      //IE only feature
      let documentBody = <any>doc.body;
      if (!documentBody.createTextRange) {
         let range = documentBody.createTextRange();
         range.moveToElementText(element);
         range.select();
      }
    };