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 */
}
Thanks for working this out @Nevor, another big thumbs up for this suggestion! Our codebase could really benefit from this feature.
Most people coming from functional languages may first think of an addition closer to #186 (crazy thoughts of a TypeScript pre-processor were thought). But this tagged union (literally) approach seems much more idiomatic and a perfectly natural extension of TypeScript.
Are there any steps we could take to help with this? Any open questions to explore? What is missing?
:+1:
Accepting PRs. With something like this, please include lots of tests with your PR :smile:
Yay! :grinning:
Can we clarify the intended scope? As far as I can tell, this issue brought up the following main ideas:
- Singleton types in the form of string literal types
- Singleton types in the form of const-enum members
- Allow type refinement by tag inspection (
foo.kind === "name") - Allow for
switch-casestatements to serve as type guards
Which of these are within scope for a suggested implementation? Does it make sense to tackle 1. and 2. together? Should 3. be treated as part of #1007?
1 and 3 only, I think. 2 is probably separable; 4 is covered by #2388
We may consider this for boolean literal types as well. They could be very useful for generators, as per issue https://github.com/Microsoft/TypeScript/issues/2983
I'm wondering whether this would allow forwarding to string literal overloads such as document.createElement. treating such overload sets like a reusable way to map runtime strings to compile-time interfaces, so for example, the caller can specify the type once (as a string literal) and have it checked both at compile and runtime:
function safeQuerySelector<TTagName /* constraint? */>(sel: string, tagName: TTagName) {
// To discover what createElement would return, given string type tagName
var elem = ((x?: void) => x ? document.createElement(tagName) : null)();
// actually do the query
elem = <typeof elem>document.querySelector(sel);
// validate that the found element is of the desired type
if (!elem || elem.nodeName !== tagName.toUpperCase()) {
throw new Error(`Selector ${sel} does not identify a ${tagName} element`);
}
return elem;
}
var a = safeQuerySelector(".crazyLink", "a");
a.href = "blah"; // fine, as safeQuerySelector returned HTMLAnchorElement
But TTagName needs a constraint to ensure that it is a string. TTagName extends string is presumably wrong because it allows anything structurally compatible with string, which is not strict enough for DOM methods that want a real string.
Wouldn't be ideal to have to manually write down the union of all parameters acceptable to createElement:
function safeQuerySelector(
sel: string,
tagName: string|"a"|"abbr"|"acronym"|"address"|"applet"
//... and so on for ~100 cases
@danielearwicker Actually, extends string would mean that it is really a string. Something structurally compatible with a string does not satisfy extends string. The one you are thinking of is extends String (note the capitalization). That is the structural one.
I'm just wondering how it should be dealt with if we want to extend the type with more string literals.
Use case:
type Event = "click" | "drag" | "touch";
declare function addEventListener(event: Event);
addEventListener("click");
createEvent("dbclick");
addEventListener("dblick"); // error
We don't have a way to augment a type declared by a type alias, whether or not it's a union type. You'd have to do what @jbondc suggested.
I'd like to clarify something about my interpretation of the proposal. Somebody please correct me if I'm wrong:
- A string literal in type position denotes the string literal type associated with the given text
- A string literal in a value position that is not contextually typed has type
string - A string literal in a value position contextually typed by a string literal type (or union thereof) has the string literal type associated with the text in the expression
- Unlike the relation between enums and
number,stringis neither assignable to nor a subtype of a string literal type.
(5). The apparent type of a string literal type is the String interface type.
No, you are talking about constant propagation, which is based on how a certain entity is declared (whether it has the const keyword or not determines whether it is a string literal type or not). I am talking about flowing this information via types, and doing the discrimination based on contextual typing info. This is what we have done for tuples vs arrays. Namely, an array literal contextually typed by a tuple type has a tuple type. In a similar way, a string literal contextually typed by a string literal type has a string literal type (the thing you are calling a set type). This is in order to maintain backward compatibility.
I will add that unless I misunderstood your proposal, the difficulty is that it does not maintain the same overload selection rules when you pass a string literal as an argument to a call.
Yes, while it doesn't seem like typing const-declared strings as string literal types would be a problem, it unfortunately is:
function foo() {
const a = "hello";
return a;
}
var x = foo();
x = "world";
Here, a would be typed as "hello", so foo's return type is now "hello". In turn, x is typed as "hello", but now x cannot be reassigned any other string.
@DanielRosenwasser With the contextual typing approach, you could still run into a similar thing. I'm modifying your example a bit to add a type annotation:
function foo(): "hello" {
return "hello";
}
var x = foo(); // Inferred as "hello"
x = "world"; // Still an error
If you wanted x to be of type string, you would have to add a widening rule that all string literal types widen to string. But I'm not sure we would want that.
With the contextual typing approach, you could still run into a similar thing.
But at that point you've opted into an explicit string literal type, whereas having const declarations implicitly do so is a breaking change, so I'm not seeing the issue in that case.
Yes, I agree. Just wanted to make sure.
I don't think that would be intuitive for users (it is inconsistent between types of declarations), but I can see some merits to that approach.
Neither the contextual type approach nor the widening approach results in different treatment for const declarations versus variable declarations. Unless somebody voices a clear advantage for the widening approach, I favor contextual typing.