microsoft / microsoft/TypeScript
Can't constrain a generic parameter to have string keys?
Personne n'a encore pris cette issue.
- Langage dominant
- Go
- Étoiles
- 111k
- Forks
- 14.3k
- Merge moyen
- 2 j 4 h
- PR mergées (30 j)
- 132
Description
Bug Report
Search Terms: Type 'X' cannot be used to index type 'Y', constrain generic parameter to have string keys
- This is the behavior in every version I tried
Code
This type is meant to map another type's values to arrays of {message: V} but also allow {message:unknown} for other string keys.
type Example<M> =
{ [K in keyof M]?: {message: M[K]}[] } &
{ [key in string]: {message: unknown}[] };
For example, the intent is that Example<{ foo: string }> should become
{
foo: {message: string}[];
[key: string]: {message: unknown}[];
}
And this works: we know that "foo" and other strings are valid keys.
const obj: Example<{foo: string}> = {};
obj["foo"] = [{message: "hi"}];
obj["bar"] = [{message: "x"}];
But trying to use Example with a generic parameter gives errors. Even if we don't know M["foo"], we should know that keyof M is string.
// attempt to constrain M's keys to be strings
function test<M extends {[key in string]: unknown}>() {
const obj: Example<M> = {};
obj["foo"] = []; // error: Type '"foo"' cannot be used to index type 'Example<M>'.
obj["bar"] = []; // error: Type '"foo"' cannot be used to index type 'Example<M>'.
}
// should fail, but doesn't -- we've tried to constrain M to have string keys
test<{ 4: string }>();
🙁 Actual behavior
Example<M> cannot be indexed using string when M is a generic parameter.
🙂 Expected behavior
It should always be possible to index with string, since the definition of Example includes { [key in string]: ... }.
Guide de contribution
Ouvrir le guide de contribution
Par où commencer
- Lisez l'issue en entier, puis le guide de contribution du projet.
- Signalez en commentaire que vous la prenez — cela évite que deux personnes fassent le même travail.
- Forkez le dépôt et travaillez sur une branche.
- Ouvrez une pull request qui référence le numéro de l'issue.
Piste de recherche
Commencez par la reproduction liée dans TypeScript Playground et comparez le cas concret Example<{ foo: string }> avec le cas générique test<M extends { [key in string]: unknown }>(). Étudiez le comportement de l’accès indexé générique et des contraintes de clés ; le travail est terminé lorsque l’indexation avec string fonctionne pour le Example générique, tandis qu’une instanciation avec une clé numérique est rejetée.
Rédigé par le modèle d'indexation à partir du texte de l'issue.
Évaluation
- Stack technique
- typescript
- Domaine
- compilers
- Type d'issue
- Bug
- Difficulté
- 4/5
- Temps estimé
- 3-5 jours
- Activité
- À l'abandon
- Clarté
- Clairement spécifiée
- Accessibilité débutants
- 35/100