11/14/212

Notes:
  • Constant expressions
  • Enum value expressions; literal or expr
  • Enum type just alias for number/string in assignment compat
  • Enum values only unique literals
  • Enum is its own map
  • Always emit unless 'declare' modifier used

// Number based enums 
enum Weekday {
  Monday: 0,
  Tuesday: 1
  AnyDay: Weekday.Monday | Weekday.Tuesday
}
 
// String-based enums
enum Weekday {
  Monday: "Monday!!!!",
  Tuesday: "Tuesday????"
}
 
// Shorthand for string-based enums, this means the same as above
enum Weekday {
  "hello world",
  "Tuesday!!!"
}
 
// Enums introduce a type
// Also, the raw string value can be assigned to an enum
var x: Weekday = "Monday";
 
// Enums provide provide access to values using lookup, regardless of underlying type
var x: Something = Weekday.Monday;
var x: Something = Weekday["Monday"]; // should be an error
 
// Integer enums can have un-numbered slots.  
// Values are auto-incremented from previous numbered slot
enum Weekday {
  Monday: 1,
  Tuesday
} // 1 and 2
 
// Enum with no values is treated as integer enum starting at 0
enum Weekday {
  Monday,
  Tuesday
} // 0 and 1
 
// Automatic conversion from underlying type to enum type
enum Method { "GET", "POST", "PUT", "DELETE" }
declare function getMethod(): string;
var method: Method = getMethod(); // Okay to convert from string
 
// However, it is an error to assign a literal that is not one of allowed values
var method: Method = "GETT"; // Error - "GETT" is not legal value of Method

document.createElement("Div")
 
//Enum values are inlined during compilation
var x: Something = Weekday.Monday;
//...becomes...
var x = 0;
	 
// The above means that enum declarations themselves generate no code, they are erased at compile time

12/5/2012

Current thinking is to support only numbers (and not strings), using this translation approach.

This enum:
enum Day { Monday: 0, Tuesday: 1, "Wed nes day": Day.Monday | Day.Tuesday, }
// LHSes can be anything that is a valid Object Literal LHS *except* a number
Translates to:
var Day;
(function(Day) {
   Day[Day.Monday = 0] = "Monday";
   Day[Day.Tuesday = 1] = "Tuesday";
   Day[Day["Wed nes day"] = Day.Monday | Day.Tuesday] = "Wed nes day";
})(Day = {});

Typing:
  • Enums are branded subtypes of number

Last edited Jan 4, 2013 at 8:19 PM by jonturner, version 9

Comments

No comments yet.