microsoft / microsoft/TypeScript

`// @ts-mutate` decorator/directive

Open
#61,179 13 comments 2 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Awaiting More Feedback Suggestion
Dominant language
Go
Stars
111k
Forks
14.3k
Avg merge
2d 4h
Merged PRs (30d)
132

Description

🔍 Search Terms

mutate type, alter type, post-declaration narrow

✅ Viability Checklist
⭐ Suggestion

When doing property assignment to a variable already typed, allow a // @ts-mutate above the assignment which will

  • A) Not throw an error trying to assign to a non-existent property
  • B) Further narrow the type, encompassing the change

Example:

interface ObjectType {
  bar: string
}

const foo: ObjectType = { bar: 'hello' }

// @ts-mutate
foo.baz = 'hello'

foo
// ^? -- this is now `ObjectType & { baz: string }`
📃 Motivating Example

One specific example of why this would be useful would be a query constructor for type inference. There are GraphQL query constructors out there (GenQL) that query by supplying an object. I've built functions that yield reusable queries but sometimes I want to extend them.

This would allow me to take an existing query object and add an additional field to query, keeping my strict type inference.

💻 Use Cases
  1. What do you want to use this for?

This could be used for constructing large objects sequentially and with inference without having to basically duplicate the information

  1. What shortcomings exist with current approaches?

If you have an existing variable, you have to alter its type declaration with the type that it is (explicitly) and intersect it with your changes. This also doesn't necessarily narrow correctly. There's no exisiting clean, easy way to do this that works off of type inference and narrowing

  1. What workarounds are you using in the meantime?
     // UGLY
     const query: ReturnType<typeof queryProp> & { prop: { addition?: true } } = queryProp(...args)
     query.prop.addition = true

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

The issue does not identify implementation files, tests, or entry points. Start by reviewing the proposed @ts-mutate behavior and its interaction with assignment checking and type narrowing; the work is done only after the design is accepted and the requested inference behavior is covered by tests.

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
Needs clarification
Newbie friendliness
25/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.