Skip to content

Incorrect initialization type checking for conditional type #40405

@wheercool

Description

@wheercool

TypeScript Version: >=3.9.2

Search Terms:
initialization type check, conditional type
Code

/**
 *  Type that allows to create a Tree with different shape and controllable level of deepness
 * */
type Length<T extends any[]> = T['length']
type Prepend<V, T extends any[]> = ((head: V, ...args: T) => void) extends ((...args: infer R) => void)
  ? R
  : any;

/* BuildTree allow to create tree with predefined level of nesting */
type BuildTree<T, N extends number = -1, I extends any[] = []> = {
  1: T
  0: (T & { children: (BuildTree<T, N, Prepend<any, I>>)[] })
}  [ Length<I> extends N ? 1 : 0]

interface User {
  name: string;
}

type GrandUser = BuildTree<User, 2>;

const grandUser: GrandUser = {
  name: 'Grand User',
  children: [{
    name: 'Son',
    children: [{
      name: 'Grandchild',
      children: [{
        name: '123',
        children: [{
          name: 'Some other name'
        }]
      }]
    }]
  }]
};

grandUser.children[0].children[0].children[0]

Expected behavior:
Compiler should complaint about children field in 'Grandchild' during grandUser variable initialization.
Actual behavior:
Compiler works correctly for the next line grandUser.children[0].children[0].children[0], but not for initialization.

Playground Link: https://www.typescriptlang.org/play?ts=3.9.2#code/PQKhCgAIUyBUCeAHAppALgCwIbstgGwIHsB3AZw2MgGMAnFXNUgSy0gBMWAzblBgHZ5yOVPgEdaxIXWJFsAIwJplANxQFIxbpxQokAlOXJQYIYOHTI0AGRQCA5lgA8cSCgAe6ex0rYBCADaALoAfJAAvPCBAOTKjlgxwZbWkAAKDKgSzgBqADTw7l4+fgEh4VEAFJWYjBwAXJD5kAB0bdh0DuSNcACUkeGqxCwc-Z7eEpTVbS0dXY0sAnx0kABK-RGDw6NQkAD8a7uN-ggA3ODgoJAAQgCuLAQccAxohCSkVLQMTBgvkKzsJAMDgobiLFCSNQaLQ6QzkdCLBzQCxWMR3B5PF6uAoAOSKE18kAEtwAtgp+JFIABaACMBQAkviSuIgsFKeVKQBvXY0nq7AAMjUqbgAZJBObRMBjBEL0Y9nnpsZAcQUMvofM4TgzQqFeiFIABfXrgA2wQKQOwJTDOenhcbMvEHGmQRr85LgRbeOjcbA0NAAVXIFO5sAE2BJKEa8LoiPOBouqLQAHE6P4OIGKVE5ZjFRm6AUAEyhc7gGjSeGQBypiR5xoptN5rm7MMRxoxesSSB5mJ5XY0KWPGWQQIh2BE8ORyAxADK0h7u1g-el9kaI4XY5bk-b1ck5DnvbHY6Xg5Xw9Hh9DE7bNILAGZ5xejwOOEO14-D5u27OI1osBTNzE66HgaySPiB67gbA4EGiWVYNkGdAtMeL72IEbpIc+ghocEGHLgI2FAA

Looks like regression, because in 3.8.3 it works correctly

Metadata

Metadata

Assignees

Labels

Fix AvailableA PR has been opened for this issueNeeds InvestigationThis issue needs a team member to investigate its status.RescheduledThis issue was previously scheduled to an earlier milestone

Type

No type

Projects

No projects

Relationships

None yet

Development

No branches or pull requests

Issue actions