Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Type inference with conditional for array fails for literal #39162

Open
Axure opened this issue Jun 19, 2020 · 1 comment
Open

Type inference with conditional for array fails for literal #39162

Axure opened this issue Jun 19, 2020 · 1 comment
Labels
Needs Investigation This issue needs a team member to investigate its status.
Milestone

Comments

@Axure
Copy link

Axure commented Jun 19, 2020

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:

@dragomirtitian
Copy link
Contributor

Just as a workaround you can use NoInfer as suggested by @jcalz here

type NoInfer<T> = [T][T extends any ? 0 : never];
function func<T>(opt: {
  value: T;
  arrayValue: NoInfer<T extends any[] ? T : T[]>;
}) {}

func({
  value: [1, 2, 3],
  arrayValue: [1, 2, 3],
})

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

func(obj);

Playground Link

@RyanCavanaugh RyanCavanaugh added the Needs Investigation This issue needs a team member to investigate its status. label Jun 22, 2020
@RyanCavanaugh RyanCavanaugh added this to the Backlog milestone Jun 22, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Needs Investigation This issue needs a team member to investigate its status.
Projects
None yet
Development

No branches or pull requests

3 participants