Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Suggestion: Add an auto_init_properties flag, emitting error if default value cannot be determined #19750

Closed
mgenware opened this issue Nov 5, 2017 · 1 comment
Labels
Out of Scope This idea sits outside of the TypeScript language design constraints

Comments

@mgenware
Copy link

mgenware commented Nov 5, 2017

This is related to #8476. I'd suggest that, under some flags, instead of warning user of type safety caused by the default undefined value, give it a default value like C#, if the default value can't be determined, emit an error.

// under a flag like `--auto_init_properties`
class Person {
  id: number; // auto initialized to 0
  name: string; // auto initialized to ""
  description: string|null; // auto initialized to null

  // **Compilation error: Can't determine default value for this prop, all properties must be initialized. **
  opt: string|number|Option; 

  // To fix this, user must specify an value, for example:
  opt: string|number|Option = 'abc';
  opt: string|number|Option = new Option();
}

In this way, all properties are actually defined in runtime:

const obj = new Person();
for (const property in obj) {
  console.log(property);
}

// Output: id, name, description, opt

Also, we don't need to write boilerplate code to enforce strict type safety:

class Person {
  constructor {
    this.id = 0;
    this.name = '';
    this.description = null;
    this.opt = new Option();
  }
}
@Ghabriel
Copy link

Ghabriel commented Nov 5, 2017

From the TypeScript Design Goals page, one of the non-goals of TS is to "Add or rely on run-time type information in programs, or emit different code based on the results of the type system," which I believe applies to your suggestion.

@ghost ghost added the Out of Scope This idea sits outside of the TypeScript language design constraints label Nov 6, 2017
@mgenware mgenware closed this as completed Nov 8, 2017
@microsoft microsoft locked and limited conversation to collaborators Jun 14, 2018
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
Out of Scope This idea sits outside of the TypeScript language design constraints
Projects
None yet
Development

No branches or pull requests

2 participants