microsoft / microsoft/TypeScript

Strict index signatures option

Offen
#56,378 3 Kommentare 0 Reaktionen 0 zugewiesene Personen Auf GitHub ansehen

Dieses Issue hat noch niemand übernommen.

Awaiting More Feedback Suggestion
Vorherrschende Sprache
Go
Sterne
111k
Forks
14.4k
Ø Merge
1 T. 19 Std.
Gemergte PRs (30 T.)
117

Beschreibung

🔍 Search Terms

strict index signatures

✅ Viability Checklist
⭐ 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
  1. What do you want to use this for?
    I want to trust TypeScript's inference in common cases

  2. What shortcomings exist with current approaches?
    Unsoundness without any red-flag features like typecasts, mutation, aliasing

  3. What workarounds are you using in the meantime?
    Manually checking for this bug 😕

Beitragsleitfaden

Beitragsleitfaden öffnen

Erste Schritte

  1. Lies das ganze Issue und danach den Beitragsleitfaden des Projekts.
  2. Schreib ins Issue, dass du es übernimmst — das erspart doppelte Arbeit.
  3. Forke das Repository und arbeite in einem Branch.
  4. Öffne einen Pull Request, der die Issue-Nummer nennt.

Rechercherichtung

Beginne mit der Prüfung von Issue #7029 und reproduziere das motivierende Beispiel mit dem TypeScript-Compiler. Da keine Implementierungsdatei oder kein Testpfad angegeben ist, lokalisiere zunächst den Checker-Bereich und die relevanten Type-System-Tests, bevor du die genaue Semantik der Option vorschlägst. Als abgeschlossen gilt die Arbeit, wenn das Verhalten für direkte Literale, inferierte Objekttypen und Interfaces spezifiziert und durch Tests abgedeckt ist.

Vom Indexierungsmodell aus dem Issue-Text verfasst.

Bewertung

Tech-Stack
typescript
Bereich
compilers
Issue-Typ
Feature
Schwierigkeit
5/5
Geschätzter Aufwand
Über eine Woche
Aktivitätsstatus
Veraltet
Klarheit
Größtenteils klar
Anfängerfreundlichkeit
28/100

Neue Issues direkt in Ihr Postfach

Eine kurze Übersicht über anfängerfreundliche GitHub-Issues.