直到 TS 允许基本算术运算number
类型,您可以使用减量计数器,例如Decr
对于具有特定深度的所有递归类型:
type Decr = [never, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10] // add to a reasonable amount
type Recurse<N extends number> = N extends 0 ?
{ foo: string } :
{ foo: string; sub: Recurse<Decr[N]> }
function recurse<N extends number>(depth: N): Recurse<N> {
if (depth === 0) return { foo: 'hey' } as Recurse<N>
return {
foo: 'hey',
sub: recurse(depth - 1),
} as Recurse<N>
}
type Decr9 = Decr[9] // 8
// compiles now
const qux = recurse(5)
const qux0: { foo: string } = recurse(0)
const qux1: { foo: string, sub: { foo: string } } = recurse(1)
const qux2: { foo: string, sub: { foo: string, sub: { foo: string } } } = recurse(2)