microsoft / microsoft/TypeScript

Feature: Lazy object initialization

Abierto
#28,503 1 comentario 43 reacciones 0 asignados Ver en GitHub

Nadie ha tomado este issue todavía.

In Discussion Suggestion
Lenguaje dominante
Go
Estrellas
111k
Forks
14.4k
Merge medio
1 d 19 h
PR fusionados (30 d)
117

Descripción

Search Terms

lazy object initialization

Suggestion

Introduce ability to initialize objects lazily and check if it was initialized.
I suggest new keyword lazyof (or other name) which would work as following:

  • You can assign Partial<T> to lazyof T.
  • Only property from type T can be assigned to lazyof T.
  • Compiler should keep track of what properties were assigned to variable of type lazyof T.
  • Every time you reference variable with type lazyof T it should be treated as if it's type was { properties, which, you, assigned, up, to, this, point }. This implies that when you assign such variable to other variable/return it, the implicit type should be latter (see example 1 and 2).
  • When lazyof T variable goes out of scope, compiler should check if all the required properties of T are set.

Use Cases

  1. Initializing objects like this:
const obj = {};
obj.foo = 1;

is common practice in JS. It would be nice to have a proper type checking

  1. Easier migration from JS to TS. You don't need to convert lazy object initialization to eager.

  2. Eager object initialization is not always the simplest approach and might complicate code

  3. Ability to check whether object was properly initialized in constructor/named constructor (see last example)

Examples

Simple example:

const obj: lazyof { [key: string]: any } = {};
obj.foo = 1;
const otherObj = obj; // otherObj implicit type is { foo: number }
obj.bar = 'a';
const otherObj2 = obj; // otherObj2 implicit type is { foo: number, bar: string }

Implicit function return type:

function initialize() {
  const obj: lazyof { [key: string]: any } = {};
  obj.foo = 1;
  obj.bar = 'a';
  return obj; // function initialize implicit return type is { foo: number, bar: string }
}

With specific interface:

interface Obj {
  foo: number;
}
const obj: lazyof Obj = {};
obj.foo = 1;
obj.bar = 'a'; // error, property bar doesn't exists on Obj.

Going out of scope:

interface Obj {
  foo: number;
  bar: string;
}
function initialize(obj: lazyof Obj) {
  obj.foo = 1;.
  // error. obj variable goes out of scope, but { foo: number } is not assignable to Obj
}

Check if object instance is initialized:

class Obj {
  foo: number;
  bar: string;
  private constructor() {}
  static namedConstructor(): Obj {
    const self: lazyof Obj = new Obj;
    self.foo = 1;
    console.log(obj.bar); // // error, property bar doesn't exists on { foo: number }
    return self;
    // error. self variable goes out of scope, but { foo: number } is not assignable to Obj
  }
}

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

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 revisando el compilador de TypeScript y el diseño de comprobación de tipos relevante para la asignación de variables, el seguimiento de propiedades, los tipos inferidos y las comprobaciones de ámbito; el issue no especifica archivos ni pruebas concretos. Se considera terminado definir e implementar el comportamiento lazyof propuesto, incluidas las restricciones de asignación, la evolución de los tipos inferidos, los errores de acceso a propiedades y la validación cuando una variable sale del ámbito.

Escrito por el modelo de indexación a partir del texto del issue.

Evaluación

Stack tecnológico
javascript, 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.