Closed
Description
π Search Terms
inference recursive reverse mapped type tuples arrays
π Version & Regression Information
- This is the behavior in every version I tried
β― Playground Link
π» Code
type Schema = Record<string, unknown> | readonly unknown[];
type Definition<T> = {
[K in keyof T]: (() => T[K]) | Definition<T[K]>;
};
declare function create<T extends Schema>(definition: Definition<T>): T;
const result = create({
a: () => 1,
b: {
c: () => "",
},
});
// this one nicely infers `{ a: number; b: { c: string } }`
result;
// ^?
const result2 = create([() => 1, [() => ""]]);
// this one infers `number[]` but it should infer `[number, [string]]`
result2;
// ^?
const result3 = create({
a: () => 1,
b: [() => ""],
});
// this one infers `{ a: number, b: string[] }` but it should infer `{ a: number, b: [string] }`
result3;
// ^?
π Actual behavior
tuples can't be inferred recursively here
π Expected behavior
tuples are inferred as arrays
Additional information about the issue
I understand that I need some tuple context to actually infer tuples but I've tried a couple of ways to add it and I just can't make it work. It would be much simpler if TS would just infer tuples here with the original code.
- an attempt with
const
type parameter: TS playground - an attempt with adding a constraint to
Definition
: TS playground - "routing"/resolving the
T[K]
's constraint using a conditional type to satisfy theDefinition
's constraint: TS playground - an attempt with changing
Schema
to useany
overunknown
to fix the recursive constraint problem: TS playground - an attempt with a separate mapped type for the array constraint and routing to it: TS playground