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

Default to single literal type whenever value is omitted #20500

Closed
agyemanjp opened this issue Dec 6, 2017 · 4 comments
Closed

Default to single literal type whenever value is omitted #20500

agyemanjp opened this issue Dec 6, 2017 · 4 comments
Labels
Out of Scope This idea sits outside of the TypeScript language design constraints

Comments

@agyemanjp
Copy link

Consider the interface:

interface xyz {
  num: 1
  str: "ok"
}

Currently the following snippet generates a type error:
let foo: xyz = {}

My proposal is the whenever a variable is declared to contain only one possible value, that value should be assumed whenever the variable's value is not specified. So, the above snippet would then not generate an error, but this would:
let foo: xyz = { num: 2 }

This proposed feature will make it easier to write clearer and simpler TypeScript code.

@ghost
Copy link

ghost commented Dec 6, 2017

That would require changing the semantics of JavaScript. See the design goals.

@ghost ghost added the Out of Scope This idea sits outside of the TypeScript language design constraints label Dec 6, 2017
@agyemanjp
Copy link
Author

I don't quite understand what is meant "that would change the semantics of JavaScript". All TypeScript is a type checker; what I mean is that for purposes of type checking, the variable should be assumed to be of the proper type if it does not have a value assigned. This should not have any effect on the code generated.

In fact what I'm proposal is already done in TypeScript to some extent. Consider this code snippet

let xyz = class {
  x: string
  y: "ok"
  z: number
}
let ok = new xyz().y

This code does not generate an error, although new xyz().y , and hence ok do not have any value assigned

@ghost
Copy link

ghost commented Dec 6, 2017

Oh, I thought you meant to fill the value in.
I don't wee why we should allow you to omit a field of a literal type, though. If you access the field you will get an error at runtime because you get undefined instead of the value you were expecting.
As for the second error you show, see #20166.

@typescript-bot
Copy link
Collaborator

Automatically closing this issue for housekeeping purposes. The issue labels indicate that it is unactionable at the moment or has already been addressed.

@microsoft microsoft locked and limited conversation to collaborators Jul 3, 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