microsoft / microsoft/TypeScript

Suggestion: assigning index signature to object with optional properties should error if value types mismatch

Offen
#42,719 4 Kommentare 3 Reaktionen 0 zugewiesene Personen Auf GitHub ansehen

Dieses Issue hat noch niemand übernommen.

In Discussion Suggestion
Vorherrschende Sprache
Go
Sterne
111k
Forks
14.3k
Ø Merge
2 T. 4 Std.
Gemergte PRs (30 T.)
132

Beschreibung

Suggestion

Moving this here from a Twitter discussion with @RyanCavanaugh: https://twitter.com/SeaRyanC/status/1359194486601994241

🔍 Search Terms

  • index signature
  • partial
  • optional

✅ Viability Checklist

My suggestion meets these guidelines:

  • 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 feature would agree with the rest of TypeScript's Design Goals.

⭐ Suggestion

Currently this does not error:

const a: { [key: string]: string } = { foo: 'bar' };
// Expected error here but got none
const t: { foo?: number } = a;
// Runtime type is `string`
// TS type is `number | undefined` ❌
console.log(t.foo);

https://www.typescriptlang.org/play?#code/MYewdgzgLgBAhgLhgbxgbQNYFMCeToBOAlmAOYC6+UxZMAvjALwowBmIISA5AEZwFd6AbgBQAejEwAogA8ADlmBQsAExhYCBEARgALDVhg8ArrFIhYYcFhGhIsKElTsQAfiRhjAWx4b6TeFEJGAAlYzAoIi9DKBwFGCIIGAADQhJSZPFJABU4w0SUzx8-AB8YcJUsVhJVZJhAGXJbcAgQABssADpWkFIACigOlwBKUSA

My suggestion is simply that TypeScript should error at the point when we try to assign the index signature type to the object that has an optional property:

// My suggestion: this should error
const t: { foo?: number } = a;

📃 Motivating Example

Currently we could run into exceptions at runtime. Example:

const a: { [key: string]: string } = { foo: 'bar' };
// Expected error here but got none
const t: { foo?: number } = a;
// Runtime exception ❗️
t.foo?.toExponential();

https://www.typescriptlang.org/play?#code/MYewdgzgLgBAhgLhgbxgbQNYFMCeToBOAlmAOYC6+UxZMAvjALwowBmIISA5AEZwFd6AbgBQAejEwAogA8ADlmBQsAExhYCBEARgALDVhg8ArrFIhYYcFhGhIsKElTsQAfiRhjAWx4b6TeFEJGAAlYzAoIi9DLBlgLDlI8BhAdXJAeD+RKAA6F1csqBBZOWsIojgAGwAKAEohIA

💻 Use Cases

This is my real world use case:

I have a type that represents URL query parameters before they have been validated/decoded:

type QueryParams = {
    [key: string]: string | string[];
};

I also have a type that represents query parameters after they have been validated/decoded:

type QueryData = {
    userId?: number;
};

I have some functions which expect QueryData, but it's very easy to make the mistake of passing in QueryParams instead.

declare const redirectToUserPage: (queryData: QueryData) => void;

declare const queryParams: QueryParams;
declare const queryData: QueryData;

// This is a mistake but TS produces no error
redirectToUserPage(queryParams);
// We should have passed in `queryData` instead

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 damit, die beiden TypeScript Playground-Beispiele zu reproduzieren und die Zuweisbarkeitsszenarien des Vorschlags für Indexsignaturen, optionale Eigenschaften und nicht übereinstimmende Werttypen zu lesen. Als abgeschlossen gilt die Aufgabe, wenn die unsicheren Zuweisungen mit einem geeigneten Typfehler abgelehnt werden und das angeforderte Verhalten mit den bestehenden TypeScript-Kompatibilitätsregeln konsistent bleibt.

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
30/100

Neue Issues direkt in Ihr Postfach

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