Alessandro Cosentino
Alessandro Cosentino

Reputation: 2364

Unexpected behaviour with enum values as types (in Typescript)

I am having troubles with understanding the way values of enums members can be used to define types in Typescript.

I understand in Typescript you can define unary types by specifying a primitive object as a type value. And enum members have numeric value associated with them.

In the following example I am aliasing the value of an enum members as the type newType. Everything makes sense, except what happens on the last line with the variable d.

const enum blah {
    test = 1,
};

type newType = blah.test;

var a: newType = 'a'; // ERROR (Type '"a"' is not assignable to type 'blah'.)
var b: newType = blah.foo; // ERROR (Property 'foo' does not exist on type 'typeof blah'.)
var c: newType = blah.test; // WORKS
var d: newType = 123; // WORKS...???

The last assignment works without error. What's an explanation for that?

(The original example came from my colleague @michaelkyriacou during a discussion about unary types in Typescript.)

Upvotes: 0

Views: 1278

Answers (2)

unional
unional

Reputation: 15619

The reason is that you are referring to a value from a variable.

What you are doing is essentially:

let x = 1 // type of x is number, not 1
type z = typeof x // the z is of type number.

Upvotes: 0

basarat
basarat

Reputation: 276393

All numbers can be assigned to an enum member. Just like all numbers can be assigned to an enum. e.g.

const enum blah {
    test = 1,
    foo = 2
};

const x: blah = 567; // allowed

Upvotes: 1

Related Questions