Skip to content

Unjustified and undetected circular type definition when using one-tuple to prevent distributive conditional type with a condition #39992

Closed

Description

TypeScript Version: 3.9.2

Search Terms: recurssive type, circular type definition, one-tuple, distributive conditional types, array, extends, conditional types

Code

type Test<T> = [T] extends [any[]] ? { array: Test<T[0]> } : { notArray: T };
declare const x: Test<number[]>;
const y: { array: { notArray: number } } = x; // Error
declare const a: Test<number>;
const b: { notArray: number } = a; // Works

Actual behavior:

Line 3 compiles with the following error:

Type '{ array: { array: { array: ...; }; }; }' is not assignable to type '{ array: { notArray: number; }; }'.

Expected behavior:

Code should compile without any error:
T = number[], i.e. the condition is true
Test<T[0]> = Test<number[][0]> = Test<number> = { notArray: number }

And indeed, as you can see from the last line - Test<number> resolves to {notArray: number}.

When removing the one-tuple from the condition:
type Test<T> = T extends any[] ? { array: Test<T[0]> } : { notArray: T }; there is no issue, but unfortunately, that leads to a different problem:

Test<boolean> is resolved to { notArray: true} | { notArray: false} (because of distributive conditional types) instead of { notArray: boolean }, which can be problematic in certain situations. According to #37279, using the one-tuple in the condition should solve this issue. I'm un-aware of a different way to do so.

Playground Link:
Playground Link

Note

Whether this is indeed a bug or not, I'll be happy for a workaround to accomplish what I want.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Labels

Fix AvailableNeeds InvestigationRescheduled

Type

No type

Projects

No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions