microsoft / microsoft/TypeScript

...args should not be readonly within function body

Open
#53,398 6 comments 1 reaction 0 assignees View on GitHub

Nobody has claimed this yet.

Experience Enhancement Suggestion
Dominant language
Go
Stars
111k
Forks
14.4k
Avg merge
1d 19h
Merged PRs (30d)
117

Description

Bug Report

🔎 Search Terms

readonly parameter inferred tuple array args variadic

🕗 Version & Regression Information
  • This is the behavior in every version I tried
⏯ Playground Link

Playground Link

💻 Code
declare function callFn<T extends readonly any[]>(args: T, fn: (...args: T) => void): void;

declare const input: readonly string[];

callFn(input, (...args) => {
    args; // readonly string[] ?
})

declare function callFnNonGeneric(args: readonly string[], fn: (...args: readonly string[]) => void): void;

callFnNonGeneric(input, (...args) => {
    args; // readonly string[] ?
})
🙁 Actual behavior

...args is readonly.

🙂 Expected behavior

...args is not readonly.

When this function is called, the input will be a brand new array which can be modified without affecting the caller:

> const fn = (...args) => { args[0] = "oops" }
undefined
> const arr = ["some", "values"]
undefined
> fn(...arr)
undefined
> arr
[ 'some', 'values' ]

Split out of https://github.com/microsoft/TypeScript/pull/53258#issuecomment-1470970487

The "fix" here is to strip readonly from variadic args (at the top level). This also means the fix in #53258 can be reverted (as the real fix can be more general).

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

Start with the linked Playground example to reproduce how readonly variadic arguments are inferred, then read the discussion in PR #53258 about the related fix. Confirm that function-body rest parameters are mutable while preserving the caller's readonly array, and verify the expected behavior against the examples in this issue.

Written by the indexing model from the issue text.

Assessment

Tech stack
typescript
Domain
compilers
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Clearly specified
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.