2

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;
  } 
Alexander Mills
  • 90,741
  • 139
  • 482
  • 817
  • 1
    There is currently no such support, but [ms/TS#49886](https://github.com/microsoft/TypeScript/pull/49886), which *might* make it into TS5.0, would allow *per-file* compiler options like [this](https://tsplay.dev/WkOlJW), so maybe you could refactor your code so that the pieces to check differently reside in their own files (and you import or otherwise reference them elsewhere). Does this fully address your question? If so, I'll write up an answer. If not, what am I missing? – jcalz Dec 20 '22 at 17:32
  • yeah that could work - please write up an answer I will upvote – Alexander Mills Dec 20 '22 at 17:35

1 Answers1

2

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

jcalz
  • 264,269
  • 27
  • 359
  • 360