microsoft / microsoft/TypeScript

Type `[x, x]` is not assignable to type `x[] & { length: 2; }`

Open
#44,508 2 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

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

Description

Bug Report

This error is probably self-explanatory. Either this is supposed to work and it’s a bug, or I’m misunderstanding something in which case please feel free to close.

Type '(Record<string, any> | null)[] & { length: 2; }' is not assignable to type '[Record<string, any> | null, Record<string, any> | null]'.ts(2322)

Outer function is typed to return the latter. It calls an inner function, typed to return the former. One would assume this should work.

Possibly related: #44309

🔎 Search Terms

array literal length

🕗 Version & Regression Information

TypeScript 4.1.3

💻 Code
async function readObjectVersions
<L extends number, C extends string[] & { length: L }>
(objectPath: string, versions: C):
Promise<(Record<string, any> | null)[] & { length: L }> {
  return versions.map(version => ({ foo: 'bar' }));
}

const version1: string = 'x';
const version2: string = 'y';

async function _readObjectVersions(objectPath: string):
Promise<[ Record<string, any> | null, Record<string, any> | null ]> {
  return await readObjectVersions(objectPath, [version1, version2]);
}

_readObjectVersions('abc');
🙁 Actual behavior

The error as described above.

🙂 Expected behavior

No type error.

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 by reproducing the error with the readObjectVersions and _readObjectVersions functions in the provided TypeScript sample, using TypeScript 4.1.3. Trace how the mapped array and its length constraint are checked against the tuple return type; done means the shown call type-checks without the reported error.

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.