microsoft / microsoft/TypeScript

Type inference with conditional for array fails for literal

Open
#39,162 1 comment 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Needs Investigation
Dominant language
Go
Stars
111k
Forks
14.3k
Avg merge
2d 4h
Merged PRs (30d)
132

Description

TypeScript Version: 3.9.2

Search Terms: typescript infer array type conditional literal

Code

function func<T>(opt: {
  value: T;
  arrayValue: T extends any[] ? T : T[];
}) {}

func({
  value: [1, 2, 3],
  arrayValue: [1, 2, 3],
}); // throws error 

const obj = {
  value: [1, 2, 3],
  arrayValue: [1, 2, 3],
};

func(obj);

Expected behavior:
No error is thrown.

Actual behavior:
The commented function call throws the following error:

Type 'number[]' is not assignable to type 'number'.(2322)
input.ts(2, 3): The expected type comes from property 'value' which is declared here on type '{ value: number; arrayValue: number[]; }'

Playground Link: https://www.typescriptlang.org/play/#code/GYVwdgxgLglg9mABKSAeAKgPgBRwA5QBciA3gFCKIBuAhgDYgCmx6A3BYjQE5c0CeANXpMWiRgA8ojMABMAzpzB8A2gF1EAfkTpELNewC+ASlIGyZFBGzlKtBs0TKAjABpEAJjcBmVS47deQWEHZzdPRB8-Y3MIBDkoRDgAIwArRABeUg47EUdXD29ffx5+IXtiUIKIooN2C3ArZJSjdiA

Related Issues:

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 generic conditional-type example in the linked TypeScript Playground and compare the direct call with the call using obj. Trace the type inference and conditional-type handling involved; done means the direct call produces no error while preserving the expected inferred array types, with a regression test for the example.

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
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.