Having new as a method means that changing Animal from a flat enum (i.e. one without associated types) to one that does means only changing one side of the literal.
Also: instanceOf methods:
const ermintrude: any = Animal.Goat.new("Ermintrude", 18);
if (Animal.instanceOf(ermintrude)) {
// ermintrude is an animal
}
if (Animal.Goat.instanceOf(ermintrude)) {
// ermintrude is goat.
}
This changes the way enums with associated values (a.k.a. tagged unions) are represented in typescript.
Previously, they were raw objects, now they are classes.
This allows us to add extra methods, including handy constructors and
instanceOf
methods.The interface for the
MyEnum
type is approximately{ tag: MyEnum_tags, data: MyEnum_interface }
, whereMyEnum_tags
is exported.The tag allows us to to interesting pattern matching like switch statements.
e.g. consider an enum for
Sheep
,Goat(String, u32)
,Cat { owner: Option<String>, name: String }
The values are constructed like so:
For pattern matching, a simple tag enum is generated and exposed:
Typescript will infer the correct types of the
value.data
property:For convenience, a
new
method is also generated:Having
new
as a method means that changingAnimal
from a flat enum (i.e. one without associated types) to one that does means only changing one side of the literal.Also:
instanceOf
methods: