Singleton types under the form of string literal types
This proposal is based on a working prototype located at https://github.com/Nevor/TypeScript/tree/SingletonTypes
String literal types extended to the whole language
This change would bring singleton types created from literal string to complete recent addition of type aliases and union types. This would hopefully satisfy those that mentioned string enum and tagged union in previous PRs (#805, #186).
This addition would be short thanks to a concept that was already implemented internally for ".d.ts" files.
Use cases
Often operational distinction of function and values are done with an companion finite set of string that are used as tags. For instance events handler types rely on strings like "mouseover" or "mouseenter".
Sometimes string are often themselves operating on a finite definite set of values that we want to convey this through specifications and have something to enforce it.
And for more advanced typing, we sometimes use types themselves as informations to guide function usages, constraining a little further the base types.
Current workarounds
There is no way to create string enum for now, the workaround is to manipulate variables assigned once and for all. This does not protect from typos that will gladly propagate everywhere a string is used.
When we want to implement tagged union types for symbolic computation, we must use some number enum coupled with subtyping and casting machinery, losing all type safety.
In general, advanced type constraint are done through classes and this put us further away from simple records that would have been used in javascript.
Overview examples
type result = "ok" | "fail" | "abort";
// "string enum"
function compute(n : number) : result {
if(...) {
return "ok";
} else if (...) {
return "fail";
} else {
return "crash"; // Error, not accepted
}
}
function checkSuccess(o : result) : void { ... }
var res : result = compute(42);
checkSuccess(res); // OK
checkSuccess("crash"); // Error
res = "crash"; // Error
var message = res; // OK, message infered as string
var verbose = "Current status : " + res; // OK
// Specifications constrains
interface operationAction {
name : string;
id : number;
status : result;
}
// Usable as and with regular types
var results : result[] = [compute(3), compute(27), "ok"]; // Ok
results = ["crash", "unknown"]; // Error
type error_level = "warning" | "fatal";
interface Foo<T> {
foo : T;
}
interface Toto<U> {
value : Foo<result> | { unknown : string; value : U };
}
var foo : Toto<error_level> = { foo : "ok" }; // OK
var foo : Toto<error_level> = { foo : "crash" }; // Error
var foo : Toto<error_level> = { unknown : "Unknown error", value : "warning" }; // OK
var foo : Toto<error_level> = { unknown : "Unknown error", value : "trace" }; // Error
// Disjoint union
type obj = { kind : "name"; name : string } | { kind : "id"; id : number } | { kind : "internal" ; id : number }
var o : obj = { kind : "name", name : "foo", id : 3 }
var o : obj = { kind : "id", name : "foo", id : 3 }
// Both object are strictly distinguished by their kind
var o : obj = { kind : "unknown", name : "something" }; // Error
type classical_obj : { name : string } | { id : number };
var c_o : classical_obj = { name : "foo", id : 3 }; // A supertype of both is assignable, we lose infos
Typing specifications
- any string literal as type "s" (StringLiteralType) where s is the content of the literal.
- every StringLiteralTypes are subtypes of string, the reverse is not true.
- two StringLiteralTypes are compatible if and only if they represent the same string literal.
type ok = "ok"
var a : ok = "ok";
var b : "ok" = a; // OK
var a : ok = "no"; // Error
var c : string = a; // OK
var a : ok = c; // Error
Pitfalls and remaining work
Backward compatibility
This prototype is backward compatible (accepts programs that were accepted before) but in one case :
function ... {
if (...) {
return "foo";
} else {
return "bar";
}
}
The compiler will raise an Error saying that there is no common type between "foo" and "bar". This is because the compiler only accept one of the return type to be supertype and does not widen before. We might add a special case for StringLiteralTypes and keep other types as is, or, do some widening and therefore accept empty records for conflicting records for instance.
Error messages
It might confuse users that their literal strings are mentioned as types when they are expecting to see "string" even though this difference as no incidence on normally rejected string. The compiler might display StringLiteralTypes as "string" whenever the conflict is not involved between two StringLiteralTypes.
Extending type guards
To be fully usable to distinguish records by type tags, type guards should be extended to take into account this kind singleton types. One would expect the following to work :
type obj = { kind : "name"; name : string } | { kind : "id" ; id : number };
var o : obj = ...;
if (o.kind == "name") {
/* o considered as left type */
} else if(o.kind == "id") {
/* o considered as right type */
}
One interesting question is whether a string literal type should be nullable (allow null / undefined as a value). Right now, our type system has types for null and undefined, but these types are assignable to all types. Should string literals be an exception because they denote one particular value? The motivation is this:
interface StringWrapper {
kind: "string";
value: string;
}
interface ArrayWrapper {
kind: "array";
value: string[]
}
var v: StringWrapper | ArrayWrapper = { kind: undefined, value: ["hello"] }; // Suppose this assignment is allowed
if (v.kind === "array") {
// Clearly, v has type ArrayWrapper here
}
else {
// Process of elimination suggests that v is of type StringWrapper, but that is not true.
v.value; // string[]
}
There are 3 options:
- Null and undefined are not assignable / subtype of a string literal type or a union of string literal types. This would be intuitive, but somewhat against the grain in terms of the existing rules in the type system.
- Null and undefined are assignable, and we don't allow a string literal check to narrow a type in the false branch of a type guard construct. This is safe, but we give up some usability.
- Null and undefined are assignable, and string literal checks can narrow in both branches. This means string literal type guards are kind of fuzzy, and can be misleading at times, but they are usable, and we get to keep our type system fully nullable.
Thoughts??
Interesting dilemma! I've been thinking about this for an hour or so, and have typed up three different responses to how there was an obvious choice and the rest were evil.
I must say that the most vexing part of this code sample is // Suppose this assignment is allowed.
My selections in order of decreasing preference:
- Implement non-nullable types holistically and get choice 1 for free, choice 2 for non-nullable types.
- Go with choice 3 for now, make it an error when non-nullable types come out (this is an example of a good breaking change).
- Implement choice 3 and create a new switch
--strictTypeGuardNarrowingwhich lets people opt-in to choice 2 :bike: :house:
I don't think choice 1 fits with today's TypeScript.
I think option 1 is correct and preferrable for the kind of type-level reasoning that singleton types are able to bring to the language.
I think of a singleton type as a subset of a broader type where the subset is a single value from the broader set, ie a singleton set. null and undefined are always members of the broader set, but a singleton type is a subset and can therefore exclude these two values.
If singleton types implicitly always also include null and undefined as allowed values, they are not really singletons at all, they are 'tripletons' or something, with the weaker powers of type-level reasoning that go with that.
eg var abc: 'abc' is stating explicitly that abc can only have the value 'abc'. null and undefined are explicitly not members of this type's value set.
Is there some scenario using singleton types where assigning null and/or undefined would be useful? Or is this perhaps more an issue with the way the compiler currently works? (Or both?)
@yortus A very straightforward example that I can think of is setting the value of a variable programmatically, e.g.:
function numberRangeName(num: number)
var x: "positive"|"negative"|"zero"; // x is undefined here.
if (num > 0) {
x = "positive";
}
///etc...
return x;
}
Of course you could always have a "NotSure" in there, but then that's basically the same thing as allowing undefined, just more explicit. I know you could write this simple example slightly differently to eliminate the temporary variable, but more complex examples might require it.
@jbondc, you cannot denote the null type and undefined types explicitly today. I'm not sure there is value in adding those words in the type syntax, rather than some sort of nullability marker.
To @yortus's comment, I was going to say that null and undefined are not really in the spirit of singleton types, and having the types be nullable is just a type system limitation. But I am actually convinced by @nycdotnet's example, where the value is set after the declaration point. If we made these types non-nullable, then you would have to modify the code in that example to take advantage of var scoping:
function numberRangeName(num: number)
if (num > 0) {
var x: "positive"|"negative"|"zero" = "positive";
}
///etc...
return x;
}
But while this is a pattern we support, it's not a pattern we want to encourage.
var x: "positive"|"negative"|"zero"; // x is undefined here.
That's just an uninitialised variable. The compiler can already flag an error for this - eg:
const a; // Error: 'const' declarations must be initialized
Its also trivially easy to avoid (with no need to exploit var scoping)
function numberRangeName(num: number)
var x: "positive"|"negative"|"zero" = "zero";
if (num > 0) {
x = "positive";
}
///etc...
return x;
}
I guess there's a trade-off for the user of singletons: either they must pay the cost of initialising singleton variables to a valid value, or they must pay the cost of having to have extra type guards and checks everywhere the values are used.
I guess I was wondering if there is a useful example of allowing null/undefined in a singleton? ie where it helps express or solve a problem at hand.
Talked with @mhegazy. We think that this issue really doesn't have much to do with string literal types. Instead it has more to do with type guards that involve property accesses. To this end, our inclination is that if you have a type guard based on a property access, we will only narrow the type in the true branch. The false branch could trick us into doing a faulty process of elimination.
@JsonFreeman can you clarify what this means for whether or not the type system would consider null/undefined as valid values for singleton types?
Sure, it means that singleton types are just like any other type, in that they implicitly allow null and undefined. This minimizes friction with the rest of the type system.
I do see the merit in making singleton types not allow null or undefined. However, doing that would mean that we need to provide a way to denote a nullable singleton type. We have thought about nullability in general from time to time, but so far have not come to any promising conclusions about how it would be accomplished. For better or worse, our type system today is nullable at its very core.
Got it. Still curious to see an example illustrating why someone might want to constrain a type to a singleton value and also want it to be nullable. Bearing in mind this is all purely about compile time type checking since singleton types obviously have no runtime support.
Clarifying my last comment... I would like to know the justification for this statement:
we need to provide a way to denote a nullable singleton type
What need does a nullable singleton satisfy?
Also isn't undefined itself (as in the value of the expression void 0) an instance of both:
a) a singleton type
b) a non-nullable type
So its not like they are unprecedented.
Instead it has more to do with type guards that involve property accesses. ... we will only narrow the type in the true branch. The false branch could trick us into doing a faulty process of elimination
I don't follow the reasoning.
First, for a variable whose type is an union of singletons and a guard testing one of the values (which does not involve any property access): the fact that the value can be null or undefined should not change the fact than in the false branch, there is one less possibility. Now if you test all possibilities (with a cascade of if-then-else or a switch), you're left with an empty union, which could still denote either null or undefined (if you decide so). This can be tested with further branches, or asserted by calling a function taking precisely this empty type (a soft version of "exhaustivity modulo non-nullness" checking).
Now, if the guard in on a property access (with an initial type being typically a union of objects with a discriminator field), the same approach would still work: when testing if the property has a specific value, the false branch should have the knowledge that the corresponding case(s) in the union are no longer possible. I don't see why allowing null/undefined would affect that.
@yortus The reason it is valuable to denote a nullable singleton type is the example @nycdotnet gave: https://github.com/Microsoft/TypeScript/issues/1003#issuecomment-112094477. Like you said, in order to get around this, you have to have a sentinel value ("zero" in the example you gave), which seems kind of unnatural.
Your point about undefined being a non-nullable singleton type: That is true, but the type system treats undefined specially in two important ways, which make it not function as a precedent for non-nullable types:
- It is a bottom type.
- It gets widened when it is assigned to something.
@jbondc Your suggestion to fold in constant propagation seems to mix too many features together, and it seems to have much wider scope than the feature calls for.
The tagged union usage is the most similar thing to variant types that Typescript can have. The problem is that there are no first class "labels" in Javascript, so we use type guards instead. And then to make a label at compile time, there is a choice between using const entities (what you suggested), or types that represent constant values (what this proposal was about).
Flowtype implemented similar feature: http://flowtype.org/blog/2015/07/03/Disjoint-Unions.html
@teppeis looks nice, and demonstrates the simplicity of coding with truly disjoint unions. According to the discussion above it appears TypeScript may not allow type narrowing in the else case due to null and undefined being implicitly allowed values of every singleton type.
@teppeis , @yortus Actually, it's the same feature, the examples are very familiar since it's actually this issue that was cross posted on flow's github (https://github.com/facebook/flow/issues/135) completing an other proposal (https://github.com/facebook/flow/issues/20).
Concerning the type narrowing, the softer handling of null and undefined of TypeScript do not prevent us from doing it in the else case. Actually all examples given in this blog post should work in my proposal prototype.
@Nevor regarding type narrowing that's great if it can be done in the presence of null/undefined. Are you talking along the lines of option 3 in this comment?