microsoft / microsoft/TypeScript
Incremental type narrowing, enabling gradual object initialization
Nobody has claimed this yet.
- Dominant language
- Go
- Stars
- 111k
- Forks
- 14.3k
- Avg merge
- 2d 4h
- Merged PRs (30d)
- 132
Description
Search Terms
delayed initialization, gradual initialization
Suggestion
What if, on every assignment to either a value or a property, that the type of that value is narrowed? It's probably easiest explained with an example:
Use Cases
It means that this code for gradually initializing an object would just work:
type Person = { firstName: string, surname: string }
function f() : Person {
const p : Partial<Person> = {}
p.firstName = ""
p.surname = ""
return p; // Error: Type 'Partial<Person>' is not assignable to type 'Person'
}
Currently this code does not type check because the compiler doesn't change the type of p after the assignments to its properties.
My thinking is that, for any value x of type X : { a : unknown },
x.a = "some string"
would result in x having its type narrowed to:
X & { a : string }
This means that the partial initialization example would work. If it works for variables as well as properties then so would this:
function f(mode: "read" | "read/write") {
// ... Code ...
}
let s: string;
s = "read"
f(s)
Examples
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
The issue names no implementation file, test, or compiler entry point. Start by reviewing existing narrowing behavior for the supplied object-initialization and variable-assignment examples; done would require an agreed design and test coverage for the requested assignment narrowing.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- typescript
- Domain
- compilers
- Issue type
- Feature
- Difficulty
- 5/5
- Estimated time
- Over a week
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 25/100