microsoft / microsoft/TypeScript
Probabilistic Types
Nobody has claimed this yet.
- Dominant language
- Go
- Stars
- 111k
- Forks
- 14.3k
- Avg merge
- 2d 4h
- Merged PRs (30d)
- 132
Description
Search Terms
Probabilistic, union, supertypes
Suggestion
If a union type contains a member which is a supertype of one or more other members, the supertype subsumes those other members, but the information isn't lost. Tooling can then use that information as a hint about the expected distribution of possible values within that type.
type MetaSyntacticVar = 'foo' | 'bar' | 'baz' | string;
For the purposes of type safety, the above type is simply string. However, tools may consider 'foo' | 'bar' | 'baz' to be the most likely values for MetaSyntacticVar. An IDE might use them for autocomplete. A linter (i.e. not tsc) might flag other values as a warning. Etc.
Use Cases
A backend service offers a range of options, and I want to statically model them as a union type. Sometimes, the service adds a new option. I must either generalize the type to a string, do a type cast and tolerate some type unsafety, or release code updates in sync with all backend updates.
Examples
type MetaSyntacticVar = 'foo' | 'bar' | 'baz' | string;
const name: MetaSyntacticVar = 'qux';
================================^ IDE suggests foo, bar, or baz as I type this
================================^^^ eslint flags this as a warning (if I opt in)
Checklist
My suggestion meets these guidelines:
- This wouldn't be a breaking change in existing TypeScript/JavaScript code
- This wouldn't change the runtime behavior of existing JavaScript code
- This could be implemented without emitting different JS based on the types of the expressions
- This isn't a runtime feature (e.g. library functionality, non-ECMAScript syntax with JavaScript output, etc.)
- This feature would agree with the rest of TypeScript's Design Goals.
Contributor guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
Start by reviewing TypeScript's union-type checking and the tooling behavior described for autocomplete and linting. Determine how literal members could remain available as hints while the containing type retains its current type-safety behavior. Done means the proposal has an agreed design and covers the type checker, IDE tooling, and optional linter behavior.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- typescript
- Domain
- compilers, developer-experience
- Issue type
- Feature
- Difficulty
- 5/5
- Estimated time
- Over a week
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 25/100