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

String enum too verbose to use #14142

Closed
Dominator008 opened this issue Feb 17, 2017 · 3 comments
Closed

String enum too verbose to use #14142

Dominator008 opened this issue Feb 17, 2017 · 3 comments
Labels
Duplicate An existing issue was already created

Comments

@Dominator008
Copy link

TypeScript Version: 2.1.1 / nightly (2.2.0-dev.201xxxxx)

Code

type Axes = "x" | "y" | "z";
const Axes = {
  X: "x", // Not X: "x" as Axes
  Y: "y",
  Z: "z"
}

function test(axes: Axes) {}

test(Axes.X); // Argument of type 'string' is not assignable to parameter of type 'Axes'.

Expected behavior:
No error
Actual behavior:
Assignability error

Since Axes is declared as a const, I expect the type inference to resolve Axes.X to "x" without the need for "as Axes".

@jesseschalken
Copy link
Contributor

Axes is const, so someone can't do Axes = .., but the properties of the object referred to be Axes are still mutable, so someone could do Axes.X = "foo", which is allowed since TypeScript inferred the X property to be of type string, not "x".

There's probably a few ways to do what you want. Here's one:

type Axes = "x" | "y" | "z";
namespace Axes {
  export const
    X = "x",
    Y = "y",
    Z = "z"
}

function test(axes: Axes) {}

test(Axes.X);

You could also use an enum, but the values have to be numbers then.

@Dominator008
Copy link
Author

Dominator008 commented Feb 17, 2017

Thanks. Hmm. I think I used "x" as Axes when I tried to reassign a random string to Axes.X, so it is indeed working as intended.

Using namespace is not always ideal as it compiles to an IIFE and bloats code size. I came up with the following:

type Axes = {
  readonly X: "x",
  readonly Y: "y",
  readonly Z: "z",

}
const Axes: Axes = {
  X: "x",
  Y: "y",
  Z: "z",
}

function test(axes: Axes[keyof Axes]) {}

test(Axes.X);

Still verbose but you get the real const check.

@mhegazy
Copy link
Contributor

mhegazy commented Feb 17, 2017

String enums is tracked by #1206

@mhegazy mhegazy added the Duplicate An existing issue was already created label Feb 17, 2017
@mhegazy mhegazy closed this as completed Apr 21, 2017
@microsoft microsoft locked and limited conversation to collaborators Jun 19, 2018
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
Duplicate An existing issue was already created
Projects
None yet
Development

No branches or pull requests

3 participants