microsoft / microsoft/TypeScript
Branded literal type widened in unexpected way
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
🔎 Search Terms
literal intersection branded string
🕗 Version & Regression Information
- This is the behavior in every version I tried, and I reviewed the FAQ for entries about branded strings/literal intersections.
⏯ Playground Link
💻 Code
declare const typeKey: unique symbol;
type TypeID<Type = unknown, ID extends string = string> = ID & { [typeKey]?: Type };
function typeID<Type, ID extends string>(id: ID): TypeID<Type, ID> {
return id;
}
type KeyOf<TID extends TypeID> = TID extends TypeID<any, infer ID> ? ID : never;
type TypeOf<TID extends TypeID> = TID extends TypeID<infer Type> ? Type : never;
type Provides<P extends TypeID> = { readonly [T in KeyOf<P>]: TypeOf<P> };
// ---cut---
interface Foo {
foo(): void;
}
const Foo = typeID("Foo") satisfies TypeID<Foo>;
// ^? const Foo: TypeID<Foo, "Foo">
const Bar: Provides<typeof Foo> = {
[Foo]: {
foo() {}
}
};
🙁 Actual behavior
Fails to compile with error:
Property 'Foo' is missing in type '{ [x: string]: { foo(): void; }; }' but required in type 'Provides<TypeID<Foo, "Foo">>'.
🙂 Expected behavior
I'd expect it to compile. Rather than widening the literal type to string, I'd expect it to discard the { [typeKey]?: Type } part, since that's pretty much bogus at runtime anyway.
However, it should also not lose the type information for the generic types. For instance, if I change the declaration to...
type TypeID<Type = unknown, ID extends string = string> = ID;
...then it does compile, but so does this...
const Bar: Provides<typeof Foo> = {
[Foo]: {
// No error about missing member `foo` here!
}
};
Additional information about the issue
Possibly related to https://github.com/microsoft/TypeScript/issues/43852#issuecomment-1671115898
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 en TypeScript Playground y compara el comportamiento de los literales branded con la discusión relacionada en el issue #43852. Sigue la ruta de comprobación de tipos para las definiciones TypeID, KeyOf, TypeOf y Provides; se considera terminado cuando el ejemplo compila y sigue notificando un miembro foo faltante cuando corresponde.
Escrito por el modelo de indexación a partir del texto del issue.
Evaluación
- Stack tecnológico
- typescript
- Área
- compilers, devtools
- Tipo de issue
- Error
- Dificultad
- 5/5
- Tiempo estimado
- Más de una semana
- Estado de actividad
- Estancado
- Claridad
- Bastante claro
- Aptitud para principiantes
- 35/100