microsoft / microsoft/TypeScript

Improve Type guards to correctly work with for-of loops

Ouverte
#29,283 2 commentaires 0 réactions 0 personnes assignées Voir sur GitHub

Personne n'a encore pris cette issue.

Suggestion
Langage dominant
Go
Étoiles
111k
Forks
14.4k
Merge moyen
1 j 19 h
PR mergées (30 j)
117

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.

Guide de contribution

Ouvrir le guide de contribution

Par où commencer

  1. Lisez l'issue en entier, puis le guide de contribution du projet.
  2. Signalez en commentaire que vous la prenez — cela évite que deux personnes fassent le même travail.
  3. Forkez le dépôt et travaillez sur une branche.
  4. Ouvrez une pull request qui référence le numéro de l'issue.

Piste de recherche

Aucun fichier source ni test n’est mentionné. Commencez par reproduire les exemples TypeScript de l’issue et par suivre la manière dont le narrowing du flux de contrôle gère les variables testées via une boucle for-of. C’est terminé lorsque les cas de narrowing valides compilent, tandis que le cas montré basé sur any ne devient pas unsound.

Rédigé par le modèle d'indexation à partir du texte de l'issue.

Évaluation

Stack technique
typescript
Domaine
compilers
Type d'issue
Fonctionnalité
Difficulté
5/5
Temps estimé
Plus d'une semaine
Activité
À l'abandon
Clarté
Plutôt claire
Accessibilité débutants
30/100

Recevez les nouvelles issues par e-mail

Un résumé court des issues GitHub adaptées aux débutants.