types - Typescript enums with parameters -
i'd have strictly typed mutable objects, haxe enums.
enum color { red; rgb(r:int, g:int, b:int); rgba(r:int, g:int, b:int, a:int); }
i'd able access a
parameter if object rgba
, , can't access parameters if object red
.
i don't care if use enum
keyword or not in typescript.
is there way achieve in typescript ?
as of version 2.0, typescript supports tagged unions extent. general syntax is
type mytype = | b | c …;
where a
, b
, c
interfaces. mytype
object can of types, , no other. announcement gives quick example:
interface square { kind: "square"; size: number; } interface rectangle { kind: "rectangle"; width: number; height: number; } interface circle { kind: "circle"; radius: number; } type shape = square | rectangle | circle; function area(s: shape) { // in following switch statement, type of s narrowed in each case clause // according value of discriminant property, allowing other properties // of variant accessed without type assertion. switch (s.kind) { case "square": return s.size * s.size; case "rectangle": return s.width * s.height; case "circle": return math.pi * s.radius * s.radius; } }
however, type safety if these union types needs guarded , checked manually so-called “discriminant property type guard” example shows (checking s.kind
).
Comments
Post a Comment