microsoft / microsoft/TypeScript

Improve Type guards to correctly work with for-of loops

Open
#29,283 2 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

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

Description

Search Terms

for-of, Type Guard

Suggestion

At the moment a paradigm of call-Parameter-Testing I apply works well in case of one parameter, but if I want to shorten the testing of multiple parameters using a for-of loop the type assertion fails.

Use Cases

Correct type guarding of multiple parameters which are supposed to be the same type but to be handled differently

Examples

type generalObj<T> = {
    value: T,
};

type numObj = generalObj<number>

const isNumObj = (testObj: generalObj<any>): testObj is numObj => {
    //some logic here...
    return true;
}

const numConsumer = (param: numObj) => param;

const shouldWork = (shouldBeNumObj: generalObj<number | string>) => {
    for (const c of [shouldBeNumObj]) {
        if (!isNumObj(c)) {
            return console.error('no numObj')
        }
    }
    // error here despite the right type ensured
    numConsumer(shouldBeNumObj);
}

const doesWork = (shouldBeNumObj: generalObj<number | string>) => {
    if (!isNumObj(shouldBeNumObj)) {
        return console.error('no numObj')
    }
    numConsumer(shouldBeNumObj);
}

const shouldWork2 = (shouldBeNumObj: Array<generalObj<number | string>>) => {
    for (const c of shouldBeNumObj) {
        if (!isNumObj(c)) {
            return console.error('no numObj')
        }
    }
    numConsumer(shouldBeNumObj[0]);
}

const baseTypeNumConsumer = (param: number) => param; 
// curtesy of @nmain
const shouldWork3 = (shouldBeNum: string | number) => {
    for (const v of [shouldBeNum]) {
        if (typeof v !== "number") {
            return;
        }
    }
    baseTypeNumConsumer(shouldBeNum); // compiler error, but should be valid
}

const stringConsumer = (param: generalObj<string>) => param;

const couldBreakCode = (anyObjS: Array<generalObj<any>>) => {
    for (const c of anyObjS) {
        if (!isNumObj(c)) {
            return console.error('no numObj')
        }
    }
    stringConsumer(anyObjS[0])
}

const becauseThisFails = (anyObj: generalObj<any>) => {
    if (!isNumObj(anyObj)) {
        return console.error('no numObj')
    }
    stringConsumer(anyObj);
}

Checklist

My suggestion meets these guidelines:

  • This wouldn't be a breaking change in existing TypeScript/JavaScript code
    • Could break compilation of already error-prone code where Type testing was disabled with any
  • This wouldn't change the runtime behavior of existing JavaScript code
  • This could be implemented without emitting different JS based on the types of the expressions
  • This isn't a runtime feature (e.g. library functionality, non-ECMAScript syntax with JavaScript output, etc.)
  • This feature would agree with the rest of TypeScript's Design Goals.

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

No source files or tests are named. Start by reproducing the TypeScript examples in the issue and tracing how control-flow narrowing handles variables tested through a for-of loop. Done means the valid narrowing cases compile while the shown any-based case does not become unsound.

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
30/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.