microsoft / microsoft/TypeScript

Dynamic object key + discriminated union + typeof could have a better narrowing type

Ouverte
#37,465 0 commentaires 5 réactions 0 personnes assignées Voir sur GitHub

Personne n'a encore pris cette issue.

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

Description

Search Terms

dynamic object key, discriminated union, typeof, type inference, narrowing type

Suggestion (or is it a bug report?)

We could write a discriminated union with one of the cases is a dynamic object key. For example...

type TExample = (
  {
    [key in string]: {
      foo: number
    }
  }
  | {
    errorCode: string
  }
)

So, if the key is errorCode it could be a { foo: number } or a string. If the key is any string that isn't errorCode, it should be a { foo: number }.

Then let's check that.

const func: () => TExample = () => ... // get value from somewhere

const value = func()

if ('errorCode' in value && typeof value.errorCode === 'string') {
  value // what's the type of value here?
}

So, makes sense that the value's type should be { errorCode: string }, right?
But the type still is TExample! I think that we could have a better narrowing type, because value only shoud be { errorCode: string } on this case.

Similarly, would be nice to have that:

if ('errorCode' in value && typeof value.errorCode === 'object') {
  value // should be { [key in string]: { foo: number } }
}

As well as...

if ('errorCode' in value && typeof value.errorCode === 'number') {
    value // should be never
}

Full code on playground

Edit

I just noticed that it happens even when we are not using a dynamic object key...

type TExample = (
  {
    aaa: {
        foo: number
    }
  }
  | {
    errorCode: string
  }
)

const func: () => TExample = () => ... // get value from somewhere

const value = func()

if ('errorCode' in value && ((typeof value.errorCode) === 'number')) {
    value // type is "{ errorCode: string }" ......  what!? I think that the expected is to be "never"
}

Playground

Use Cases

I'm opening this issue because I had a problem because of this limitation.

I'm developing a client for an API and, for convention, all errors is returned as { errorCode: string }.
And on an endpoint, the json can be a { [key in string]: TComplexObject } on success case, or be a { errorCode: string } on fail case.
So normally I'm checking if I had an error using if ('errorCode' in result) {, but on this endpoint it isn't enough since we have this limitation on TS. Then I don't have a good type inference on this case, needing to write a more complex code.

Examples

type TExample = (
  {
    [key in string]: {
      foo: number
    }
  }
  | {
    errorCode: string
  }
)

const func: () => TExample = () => ({ blah: { foo: 1 } })

const value = func()

if ('errorCode' in value && typeof value.errorCode === 'string') {
  value // should be { errorCode: string }
}

if ('errorCode' in value && typeof value.errorCode === 'object') {
  value // should be { [key in string]: { foo: number } }
}

if ('errorCode' in value && typeof value.errorCode === 'number') {
  value // should be never
}

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

Commencez par les exemples TypeScript Playground liés et comparez les résultats actuels du narrowing avec les résultats demandés pour les vérifications string, object et typeof impossibles. La tâche est terminée lorsque la valeur de l’union discriminée est réduite au membre approprié, ou à never dans le cas impossible, y compris les exemples de clé dynamique et de propriété explicite.

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

Recevez les nouvelles issues par e-mail

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