You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
A very nice addition to TypeScript's type system would be sum types in the spirit of ML-like languages. This is one of basic and simple programming constructs from functional programming which you really miss once you get used to it, but which seem to have a hard time being included in new modern languages (contrary to other features from functional programming such as first-class functions, structural types, generics).
I guess the most natural way to integrate sum types in the current language syntax would be to extend enum variants with extra parameters (similarly to what Rust does: http://doc.rust-lang.org/tutorial.html#enums ) and upgrade the switch statement to a more powerful structural pattern matching (although in a first step, simply discriminating on the toplevel variant and capturing its parameters would be already quite good).
This is quite different from other the proposal about "union types" (#14), which would mostly be useful to capture types in existing Javascript APIs. Sum types are rather used to describe algebraic data structures. They would be particularly useful for any kind of symbolic processing (including for implementing the TypeScript compiler).
I would love such feature.
However from javascript perspective I think complex pattern matching could be really hard to achieve.
Even for simple example like the following one, it's hard to find javascript corresponding :
enumColor{Red,Green,Blue,Rgb(r: number,g: number,b: number)}functionlogColor(color: Color){switch(color){caseColor.RGB(r,g,b):
console.log('rgb('+r+', '+g+', '+b+')');breakdefault:
console.log(Color[color])break;}}varmyColor: Color=Color.Rgb(255,0,255);varred: Color=Color.Red;logColor(myColor);//should ouput 'rgb(255, 0, 255)'logColor(red);//should ouput 'Red'console.log(Color[myColor]);// should output 'Rgb'console.log(Color[3]);// should output 'Rgb';console.log(Color[Color.Rgb]);// should ouput 'Rgb'console.log(Color['Rgb']);// should ouput '3'
I tried to hack a little something, it seems to work but i'm not sure if it worth the outputted JS
varColor;(function(Color){Color[Color["Red"]=0]="Red";Color[Color["Green"]=1]="Green";Color[Color["Blue"]=2]="Blue";Color.Rgb=function(r,g,b){varresult=[r,g,b];result.valueOf=result.toString=function(){return3;};returnresult;};Color.Rgb.toString=Color.Rgb.valueOf=function(){return3;};Color[3]="Rgb";})(Color||(Color={}));functionlogColor(color){switch(+color){case3:
varr=color[0];varg=color[1];varb=color[2];console.log('rgb('+r+', '+g+', '+b+')');break;default:
console.log(Color[color])break;}}varmyColor=Color.Rgb(255,0,255);varred=Color.Red;logColor(myColor);//should ouput 'rgb(255, 0, 255)'logColor(red);//should ouput 'Red'console.log(Color[myColor]);// should output 'Rgb'console.log(Color[3]);// should output 'Rgb';console.log(Color[Color.Rgb]);// should ouput 'Rgb'console.log(Color['Rgb']);// should ouput '3'
note the + before the switch statement value to force the transformation trough 'valueOf'. I hope there is a better way to do that but I don't see how without breaking retrocompatibility.
I suggest an implementation that leverages the existing lookup power of objects (not using switch/case but instead using parameter names). Here's what I'm thinking of...
[Note: I've changed the example to avoid using colour as that's a bit confusing as colours are made of RGB. Example now uses Animals.]
I second that. Unions and discriminated unions are very different both in implementation and semantics. Plus, non-discriminated unions are already used a lot in actual JavaScript code out there, which gives them a much higher priority.
A major concern I have is how to effectively use types like this without adding a lot of expression level syntax for operating over them. How useful will it be if there's no 'match' type operator to nicely decompose these in a type safe manner?
Union types and sum types (i.e. disjoint tagged unions) are really different concepts, with different use cases.
Union types are certainly very important to represent faithfully the API of existing Javascript libraries, although a full support for them is tricky since you cannot in general determine type-information based on runtime values.
Sum types are more important, I'd say, to write high-level programs, not necessarily related to existing Javascript code bases, particularly for everything which pertains to symbolic processing. Having them in the language would make it a great choice for a whole new class of problems.
Dan Quirk (@danquirk) Extending the existing switch statement to allow capturing "enum arguments" would be a natural first step. See François de Campredon (@fdecampredon)'s first example. This would not introduce a lot of new expression level syntax.
and detect such situation in if and switch in the following manner
if all conditions are met:
expression of form expr.prop is compared against expression S for equality or not-equality;
syntactically expr is simple identifier (no compound expressions);
the type of the S expression is singleton string literal;
expression expr itself has type, which in every union branch has the same property named prop with singleton string literal type (not necessarily disjoint across the union branches)
then in the proper following context the type of expr is narrowed to the union of the branches where type of the prop field exactly matches the type of S (or doesn't match if the check was for non-equality), or type: { prop: S } if no alternatives found, or {prop: string} in switch/default alternative.
Thus, we will be able to write
vara: Action;// ...if(a.type==="SUCCESS"){console.log(a.data)// type of a is narrowed to {type: "SUCCESS", data: string}}
This proposal is less powerfull than full algebraic types (it lacks recursion), nevertheless it's rather pragmatic as it helps to assign the correct types to commonly used patterns in JavaScript especially for React + (Flux/Redux).
I know that narrowing is working only on simple variables, but I think this case is somewhat ideologically equivalent to the type-checking for expressions assigned to the simple variable.
This may already have a (nonsense) meaning of check if a is the same instance of this new literal. Other options:
case {type is "FAILURE", error}:, suggesting type guarding is happening, but those are not emitted.
case let {type: "FAILURE", error}:, though I'm concerned about it being too easy to miss the let.
case {type == "FAILURE", error}:, which would allow other destructurings like {opCount == 2, op1, op2}, {opCount > 3, opList}, but type = "FAILURE" (meaning default missing type in existing ES6) would, again be too close.
Alternatively: Perhaps depend on adding C++-style condition declarations (if (let foo = getFooOrNull()) foo.bar();, and allow:
if (let {type == "FAILURE", error} = a) ...
I think this is closer to how languages with pattern matching work in a way that feels like where ES is going, but it seems like (something like) it should be proposed as an ES feature first.
Basarat Ali Syed (@basarat) I have a version of our narrowing code which allows this behavior
with existing types (#6062) - but it still has some open questions.
Implementation of discriminated union types using string literal type tags is now available in #9163.
Reacted by ZpdDG4gta, Troy Gerwien, Anatoly Ressin, Linda_pp and Christoph Herzog
Reacted by Josh Abernathy, Troy Gerwien, Yegor Roganov, Lennart, Claudia Meadows, ZpdDG4gta, Sean Vieira, Ting-gian LUA, Christoph Herzog, Pauan and 1 more
Well that wouldn't do what you want in JavaScript either if x was some object literal. Your type guard would either be a set of property checks
if(x.length) { ... }
if(x.aPropertyInA) { ... }
That is a structural guard which although may be a useful feature but may not always be applicable, thus my suggestion above to use abstract class for a nominal guard instead of:
It would be nice to have a sealed keyword on an abstract class to indicate that the only subclasses intended to exist are those defined in the same project.
You can do that with a union type:
The idea is that one should be able to define the class (with methods) and the type as the same thing, rather than having separate class Super and type SuperT = Sub1 | Sub2.
Can't you just override required methods on Sub1 and Sub2 (in other words, dynamic dispatch)? Why would you want to check types?
Many people prefer a style of programming where functions are defined only once, as opposed to once per subclass. That's why this issue here exists.
Without the class Super then the only way to compile-time type that some member properties of the types in the union are equivalent is structural typing, thus it loses some of nominal typing capability.
So sealed is required for exhaustive checking where we want nominal typing and want to follow the software engineering principles of Single-Point-Of-Truth (SPOT) and DNRY, so that we don't have to declare a separate class Super and type SuperT = Sub1 | Sub2.
However, if ever nominal typeclasses were supported (a la Rust or Haskell), then the entire point of typeclasses (versus class subtyping) is to not conflate the definition and implementations of new interfaces on data type in order to have more degrees-of-freedom in compile-time extensibility. Thus, the relationship between interface structures becomes nominal and orthogonal to the definition of the data type or nominal sum type, and the extra declaration of trait Super (and implementations of Sub1 and Sub2 for typeclass Super) isn't a violation of SPOT and DNRY. So with typeclasses and if we don't formalize nominal class subtyping, then afaics sealed would be unnecessary.
This proposal is less powerfull than full algebraic types (it lacks recursion)
And it isn't compatible with nominal typeclasses; thus conflates interface (declaration and implemention) with data type, i.e. the interfaces (e.g. data: string) that each of the members of the sum type (e.g. SUCCESS) implement is not orthogonal to the declaration of the sum type Action (and such conflation doesn't exist in Rust and Haskell). Afaics, structural typing isn't compatible with maximum compile-time extensible (nor complete solutions to Wadler's Expression Problem). Merged #9163 gives us extensibility of declaring classes and interfaces which implement the discriminated union types, but it doesn't enable us to compile-time extend _existing_ classes (without editing their dependent code, e.g. a function returning a type of existing class) by providing orthogonal implementation of a typeclass.
Activity
fdecampredon commentedon Jul 22, 2014
👍
RyanCavanaugh commentedon Jul 22, 2014
+Suggestion, Needs Proposal
fdecampredon commentedon Jul 22, 2014
I would love such feature.
However from javascript perspective I think complex pattern matching could be really hard to achieve.
Even for simple example like the following one, it's hard to find javascript corresponding :
I tried to hack a little something, it seems to work but i'm not sure if it worth the outputted JS
note the
+before the switch statement value to force the transformation trough 'valueOf'. I hope there is a better way to do that but I don't see how without breaking retrocompatibility.iislucas commentedon Jul 23, 2014
I suggest an implementation that leverages the existing lookup power of objects (not using switch/case but instead using parameter names). Here's what I'm thinking of...
[Note: I've changed the example to avoid using colour as that's a bit confusing as colours are made of RGB. Example now uses Animals.]
That would approximately correspond to a JS object that is assumed to have exactly one of the following parameters, i.e. be treated a bit like:
When you define a variable of this type, e.g.
it can be compiled like so:
Then you can match in a more standard functional programming style of syntax like so:
Which would be compiled to JS like so:
That seems to provide reasonable balance of conciseness, readablity and efficiency.
RyanCavanaugh commentedon Jul 28, 2014
Can we close this as a duplicate of #14?
fdecampredon commentedon Jul 29, 2014
Ryan Cavanaugh (@RyanCavanaugh) for me it's something quite different than union type more an extension of enum.
iislucas commentedon Jul 29, 2014
Maybe worth thinking of this more like an algebraic data type?
fsoikin commentedon Jul 29, 2014
I second that. Unions and discriminated unions are very different both in implementation and semantics. Plus, non-discriminated unions are already used a lot in actual JavaScript code out there, which gives them a much higher priority.
danquirk commentedon Jul 29, 2014
A major concern I have is how to effectively use types like this without adding a lot of expression level syntax for operating over them. How useful will it be if there's no 'match' type operator to nicely decompose these in a type safe manner?
alainfrisch commentedon Jul 30, 2014
Union types and sum types (i.e. disjoint tagged unions) are really different concepts, with different use cases.
Union types are certainly very important to represent faithfully the API of existing Javascript libraries, although a full support for them is tricky since you cannot in general determine type-information based on runtime values.
Sum types are more important, I'd say, to write high-level programs, not necessarily related to existing Javascript code bases, particularly for everything which pertains to symbolic processing. Having them in the language would make it a great choice for a whole new class of problems.
Dan Quirk (@danquirk) Extending the existing switch statement to allow capturing "enum arguments" would be a natural first step. See François de Campredon (@fdecampredon)'s first example. This would not introduce a lot of new expression level syntax.
alainfrisch commentedon Sep 9, 2014
Another possible view of sum types in TypeScript would be as an extension of regular interfaces with an "exclusive-or" modality instead of an "and".
interface MySumType {
| name: string
| id: number
}
This would classify objects that contains exactly one of the mentioned fields (with the corresponding type).
This might be closer to how people would naturally encode sum types in Javascript.
iislucas commentedon Sep 9, 2014
Alain Frisch (@alainfrisch) 👍 that's the way I was coding it up in my suggestion above :)
beloglazov commentedon Sep 10, 2014
👍
29 remaining items
Artazor commentedon Jan 21, 2016
Since we have string literal types, I would propose to interpret the following declaration
as fully equivalent shorthand to
and detect such situation in
ifandswitchin the following mannerif all conditions are met:
expr.propis compared against expressionSfor equality or not-equality;expris simple identifier (no compound expressions);Sexpression is singleton string literal;expritself has type, which in every union branch has the same property namedpropwith singleton string literal type (not necessarily disjoint across the union branches)then in the proper following context the type of
expris narrowed to the union of the branches where type of thepropfield exactly matches the type ofS(or doesn't match if the check was for non-equality), or type:{ prop: S }if no alternatives found, or{prop: string}inswitch/defaultalternative.Thus, we will be able to write
or even
This proposal is less powerfull than full algebraic types (it lacks recursion), nevertheless it's rather pragmatic as it helps to assign the correct types to commonly used patterns in JavaScript especially for React + (Flux/Redux).
I know that narrowing is working only on simple variables, but I think this case is somewhat ideologically equivalent to the type-checking for expressions assigned to the simple variable.
Dan Quirk (@danquirk), what is your opinion?
weswigham commentedon Jan 21, 2016
Anatoly Ressin (@Artazor) I've already done some investigation into equality -based type narrowing - It is pretty cool to use.
DanielRosenwasser commentedon Jan 21, 2016
Anatoly Ressin (@Artazor) with Wesley Wigham (@weswigham)'s type narrowing branch, and some recent changes I've made, something like that works. It needs to happen one step at a time though.
simonbuchan commentedon Mar 15, 2016
If you're looking for matching sugar for using existing types, maybe allow destructuring in cases?:
This may already have a (nonsense) meaning of check if
ais the same instance of this new literal. Other options:case {type is "FAILURE", error}:, suggesting type guarding is happening, but those are not emitted.case let {type: "FAILURE", error}:, though I'm concerned about it being too easy to miss thelet.case {type == "FAILURE", error}:, which would allow other destructurings like{opCount == 2, op1, op2},{opCount > 3, opList}, buttype = "FAILURE"(meaning default missingtypein existing ES6) would, again be too close.Alternatively: Perhaps depend on adding C++-style condition declarations (
if (let foo = getFooOrNull()) foo.bar();, and allow:I think this is closer to how languages with pattern matching work in a way that feels like where ES is going, but it seems like (something like) it should be proposed as an ES feature first.
basarat commentedon Mar 15, 2016
FWIW Anatoly Ressin (@Artazor)'s proposal #186 (comment) is what flow does (disjoint unions) : http://flowtype.org/docs/disjoint-unions.html#_
Conditional checks on
typeallow you to narrow down the other members ofAction🌹weswigham commentedon Mar 16, 2016
Basarat Ali Syed (@basarat) I have a version of our narrowing code which allows this behavior
with existing types (#6062) - but it still has some open questions.
On Tue, Mar 15, 2016, 7:44 PM Basarat Ali Syed notifications@github.com
wrote:
ahejlsberg commentedon Jun 14, 2016
Implementation of discriminated union types using string literal type tags is now available in #9163.
shelby3 commentedon Sep 10, 2016
Aleksey-Bykov wrote:
Use an
abstract classinstead ofinterface.Dan Quirk (@danquirk) wrote:
That is a structural guard which although may be a useful feature but may not always be applicable, thus my suggestion above to use
abstract classfor a nominal guard instead of:Which appears to me to be undesirable.
Mike Stay (@metaweta) wrote:
Which is a nominal sum type (aka ADT) and employs nominal guards.
Andy Hanson (@andy-hanson) wrote:
Without the
class Superthen the only way to compile-time type that some member properties of the types in the union are equivalent is structural typing, thus it loses some of nominal typing capability.So
sealedis required for exhaustive checking where we want nominal typing and want to follow the software engineering principles of Single-Point-Of-Truth (SPOT) and DNRY, so that we don't have to declare a separateclass Superandtype SuperT = Sub1 | Sub2.However, if ever nominal typeclasses were supported (a la Rust or Haskell), then the entire point of typeclasses (versus class subtyping) is to not conflate the definition and implementations of new interfaces on data type in order to have more degrees-of-freedom in compile-time extensibility. Thus, the relationship between interface structures becomes nominal and orthogonal to the definition of the data type or nominal sum type, and the extra declaration of
trait Super(and implementations ofSub1andSub2for typeclassSuper) isn't a violation of SPOT and DNRY. So with typeclasses and if we don't formalize nominal class subtyping, then afaicssealedwould be unnecessary.Basarat Ali Syed (@basarat) wrote:
That is structural (not nominal) sum typing.
Anatoly Ressin (@Artazor) wrote:
And it isn't compatible with nominal typeclasses; thus conflates interface (declaration and implemention) with data type, i.e. the interfaces (e.g.
data: string) that each of the members of the sum type (e.g.SUCCESS) implement is not orthogonal to the declaration of the sum typeAction(and such conflation doesn't exist in Rust and Haskell). Afaics, structural typing isn't compatible with maximum compile-time extensible (nor complete solutions to Wadler's Expression Problem). Merged #9163 gives us extensibility of declaring classes and interfaces which implement the discriminated union types, but it doesn't enable us to compile-time extend _existing_ classes (without editing their dependent code, e.g. a function returning a type of existing class) by providing orthogonal implementation of a typeclass.