microsoft / microsoft/TypeScript
Can't constrain a generic parameter to have string keys?
Nadie ha tomado este issue todavía.
- Lenguaje dominante
- Go
- Estrellas
- 111k
- Forks
- 14.3k
- Merge medio
- 2 d 4 h
- PR fusionados (30 d)
- 132
Descripción
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]: ... }.
Guía de contribución
Primeros pasos
- Lee el issue completo y luego la guía de contribución del proyecto.
- Comenta en el issue que vas a ocuparte — evita que dos personas hagan lo mismo.
- Haz un fork del repositorio y trabaja en una rama.
- Abre un pull request que haga referencia al número del issue.
Línea de trabajo
Comienza con la reproducción enlazada en TypeScript Playground y compara el caso concreto Example<{ foo: string }> con el caso genérico test<M extends { [key in string]: unknown }>(). Investiga el comportamiento del acceso indexado genérico y de las restricciones de claves; se considera terminado cuando la indexación con string funciona para el Example genérico, mientras que se rechaza una instanciación con una clave numérica.
Escrito por el modelo de indexación a partir del texto del issue.
Evaluación
- Stack tecnológico
- typescript
- Área
- compilers
- Tipo de issue
- Error
- Dificultad
- 4/5
- Tiempo estimado
- 3-5 días
- Estado de actividad
- Estancado
- Claridad
- Bien especificado
- Aptitud para principiantes
- 35/100