microsoft / microsoft/TypeScript

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

Abierto
#42,719 4 comentarios 3 reacciones 0 asignados Ver en GitHub

Nadie ha tomado este issue todavía.

In Discussion Suggestion
Lenguaje dominante
Go
Estrellas
111k
Forks
14.3k
Merge medio
2 d 4 h
PR fusionados (30 d)
132

Descripción

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

Guía de contribución

Abrir la guía de contribución

Primeros pasos

  1. Lee el issue completo y luego la guía de contribución del proyecto.
  2. Comenta en el issue que vas a ocuparte — evita que dos personas hagan lo mismo.
  3. Haz un fork del repositorio y trabaja en una rama.
  4. Abre un pull request que haga referencia al número del issue.

Línea de trabajo

Comienza reproduciendo los dos ejemplos de TypeScript Playground y leyendo los escenarios de asignabilidad de la propuesta para firmas de índice, propiedades opcionales y tipos de valor incompatibles. Se considera terminado cuando las asignaciones inseguras se rechazan con un error de tipo adecuado, mientras que el comportamiento solicitado sigue siendo coherente con las reglas de compatibilidad existentes de TypeScript.

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

Recibe los nuevos issues en tu correo

Un resumen breve de issues de GitHub para principiantes.