microsoft / microsoft/TypeScript
Strict index signatures option
Nadie ha tomado este issue todavía.
- Lenguaje dominante
- Go
- Estrellas
- 111k
- Forks
- 14.4k
- Merge medio
- 1 d 19 h
- PR fusionados (30 d)
- 117
Descripción
🔍 Search Terms
strict index signatures
✅ Viability Checklist
- This wouldn't be a breaking change in existing TypeScript/JavaScript code
- 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, new syntax sugar for JS, etc.)
- This isn't a request to add a new utility type: https://github.com/microsoft/TypeScript/wiki/No-New-Utility-Types
- This feature would agree with the rest of our Design Goals: https://github.com/Microsoft/TypeScript/wiki/TypeScript-Design-Goals
⭐ Suggestion
Basically, I'm wondering if there's any interest to revisit #7029 and provide an option for an alternative balance.
To recap, the status quo is that object literal types (like {a: number}) are (intentionally unsoundly) considered assignable to index signature types (like {[k: string]: number}) as long as each property is assignable; but the exact same interface type is not:
function httpService(path: string, headers: { [h: string]: string }) { }
// A) direct object literal
httpService("/", { "Content-Type": "application/json" }) // ✅ ok
// B) object literal types
const headers = { "Content-Type": "application/json" }
httpService("/", headers) // ✅ ok
type HeadersTypeLiteral = { "Content-Type": string }
const headers2: HeadersTypeLiteral = headers
httpService("/", headers2) // ✅ ok
// C) interface type
interface HeadersInterface { "Content-Type": string }
const headers3: HeadersInterface = headers
httpService("/", headers3) // ❌ Type Error: Index signature missing...
This is totally sound for a direct object literal, of course, since we know it has no other properties (assuming no one messed with Object.prototype); but object literal types can come from anywhere, so that's pretty unsound. It's also a little surprising—I don't immediately know off the top of my head other cases where interface types vs interface literal types make such a big difference.
I understand this was an FAQ back in the day, but is there any way we could have the option of extra strictness, where direct object literals (A) above) are still assignable (they're already treated differently for excess property checks), but object literal types (B)) would behave more like interface types (C))?
Even more ideal of course would be if we distinguished between object literal types that come directly from object literal expressions in the same scope, vs inferred object literal types like cause the problem in the motivating example below. (If we did distinguish them, we could even extend excess property checks to the same-scope object literals!)
📃 Motivating Example
Consider this example, purely functional, seemingly correct types everywhere, and no typecasts (from this tweet):
function validateUsername(input: { username: string }) {
console.assert(input.username.length < 30)
return input
}
function printRecord(record: Record<string, string>) {
for (const key in record) {
const value = record[key]
console.log(`${key}: ${value.trim().toLowerCase()}`) // 💥
}
}
const account = {
username: 'person',
email: 'person@example.com',
isAdmin: false,
}
const validated = validateUsername(account)
printRecord(validated)
💻 Use Cases
-
What do you want to use this for?
I want to trust TypeScript's inference in common cases -
What shortcomings exist with current approaches?
Unsoundness without any red-flag features like typecasts, mutation, aliasing -
What workarounds are you using in the meantime?
Manually checking for this bug 😕
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 revisando el issue #7029 y reproduciendo el ejemplo motivador con el compilador de TypeScript. No se identifica ningún archivo de implementación ni ninguna ruta de pruebas, así que localiza primero el área del checker y las pruebas relevantes del sistema de tipos antes de proponer la semántica exacta de la opción. Se considera terminado cuando el comportamiento para literales directos, tipos de objeto inferidos e interfaces está especificado y cubierto por pruebas.
Escrito por el modelo de indexación a partir del texto del issue.
Evaluación
- Stack tecnológico
- typescript
- Área
- compilers
- Tipo de issue
- Nueva funcionalidad
- Dificultad
- 5/5
- Tiempo estimado
- Más de una semana
- Estado de actividad
- Estancado
- Claridad
- Bastante claro
- Aptitud para principiantes
- 28/100