microsoft / microsoft/TypeScript

negating type constraints

Open
#7,993 14 comments 24 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Awaiting More Feedback Suggestion
Dominant language
Go
Stars
111k
Forks
14.3k
Avg merge
2d 4h
Merged PRs (30d)
132

Description

Sometimes it's useful to put a limit on what a type parameter can be. In a way it is a counterpart of the extends constraint.

Problem

Consider an example, a classic function that takes whatever and returns void:

function ignore<a>(value: a) : void {};

However we must not apply this function to Promises, because it might get us a temporal leak if we do.

function readFileAsync(): Promise<string>;
ignore(readFileAsync()); // <-- untracked promise, temporal leak

Unfortunately it is way too easy to get into a situation when a promise is passed to that function unintentionally as a result of refactoring:

// before
function readFileSync(): string;
ignore(readFileSync()); // typechecks, works as intended, no problem

// after refactoring
function readFileAsync(): Promise<string>; // <-- went async here
ignore(readFileAsync()); // typechecks, unintended temporal leak, big problem
Solution

The situation above could have been avoided if TypeScript allowed negating constraints:

function ignore<a unlike Promise<any>>(value: a): void {} // <-- hypothetical syntax

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start with the proposed unlike syntax and the issue's comparison to existing extends constraints. Review TypeScript's generic constraint and type-checking behavior, then define how excluding Promise<any> should work in the shown refactoring cases; done requires an agreed design plus implementation and tests, since no files or test entry points are named.

Written by the indexing model from the issue text.

Assessment

Tech stack
typescript
Domain
compilers
Issue type
Feature
Difficulty
5/5
Estimated time
Over a week
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.