This project is read-only.

Enums and Structs

Topics: General
Oct 6, 2012 at 4:40 PM

What about enums and structs?


Oct 6, 2012 at 6:59 PM
Edited Oct 6, 2012 at 7:00 PM


This is from the language spec:

NOTE: The TypeScript compiler currently implements an experimental form of enum types. We expect the final language to support enum types, but not in the form they are currently implemented.

So as you can see built in support for enums isn't fully baked yet.  With that said you can get enum like behaviour using standard JavaScript techniques. Below I modified the Greeter example from the playground to use a new GreetingType in the same way you would an enum.  It's not an enum though because you can't enforce that only values of GreetingType be passed to greet().  We'll have to wait for official language support for that:

class Greeter {
	greeting: string;
	constructor (message: string) {
		this.greeting = message;
	greet(type: number) {
		switch (type) {
			case GreetingType.Hello:
				return "Hello, " + this.greeting;
			case GreetingType.Welcome:
				return "Welcome, " + this.greeting;				

var GreetingType = {
	Hello: 0,
	Welcome: 1	

var greeter = new Greeter("world");

var button = document.createElement('button')
button.innerText = "Say Hello"
button.onclick = function() {



There's no official concept of a struct in the language but that's what JSON objects really are.  So anywhere you would want to use a struct in your code I'd just use an interface and a plain old JSON object:

interface EmployeeData {
	name: string;
	id: string;

var employee: EmployeeData = {
	name: 'Steven Ickman',
	id: '1'


Oct 8, 2012 at 4:30 PM

TypeScript has object literals and interfaces, which compile down to JavaScript object literals (and nothing).  This would be the TS equivalent of a 'struct' as it's the closest to the JavaScript.