Search code examples
javascriptnode.jstypescripttypescript-eslintstrictnullchecks

Use 'strictNullChecks' annotation on one function/method


I have this method:

  remove(node: SortedQueueNode<V, K>) : SortedQueueNode<V, K>{

    // ...
    return node.parent;
  } 

there are multiple return statements in the function body, and I want to avoid null/undefined return statements. Is there an annotation I can add to just this method, something like:

  // @ts-strictNullChecks
  remove(node: SortedQueueNode<V, K>) : SortedQueueNode<V, K>{

    // ...
    return node.parent;
  } 

Solution

  • As of TypeScript 4.9 the --strictXXX compiler options are each either enabled or disabled; there is no support for applying them at a more granular or modular level.

    But, at microsoft/TypeScript#49886 there is an implementation of per-file compiler options, where some compiler options including --strictNullChecks can be enabled or disabled for an individual file in a project. As of today this has not been merged into the main branch, but it is part of the TypeScript 5.0 iteration plan at microsoft/TypeScript#51362, so there's a good possibility that it will be released with TypeScript 5.0. Until and unless it is released, I think you're stuck.

    If and when it is released, it wouldn't be exactly the same as a function-scoped compiler option. But you could get a similar effect to by refactoring your code so that the parts you want to check differently live in different files, such as:

    // someFile.ts    
    
    // @ts-strictNullChecks true
    // -------------------> ^^^^ change to false to see error go away
    
    Foo.prototype.remove = function <V, K>(node: SortedQueueNode<V, K>) { // error!
    //~~~~~~~~~~~~~~~~~~ <-- undefined is not assignable to SortedQueueNode<V, K>
        return node.parent;
    } 
    

    where the //@ts-strictNullChecks true compiler directive causes the whole file to be checked strictly for null/undefined-related errors, and where your remove() method is implemented in this file separately from the rest of the class.

    You can see this in action now, by using the 4.9.0-pr-49886-38 version of TypeScript: Playground link to code, 4.9.0-pr-49886-38