Skip to content

Unexpected lack of type error when the exactOptionalPropertyTypes flag is not setΒ #46258

@ugultopu

Description

@ugultopu

Bug Report

πŸ”Ž Search Terms

is:issue exactoptionalpropertytypes

πŸ•— Version & Regression Information

This changed between versions 4.4.3 and later.

⏯ Playground Link

Playground link with relevant code

πŸ’» Code

type BaseEntity = Object;

type DrillDownToEntity<T> = T extends BaseEntity ?
    T : T extends ReadonlyArray<infer U> ? DrillDownToEntity<U> : never;

type Relations<T extends BaseEntity> = {
    [K in keyof T as DrillDownToEntity<T[K]> extends never ? never : K]?: Relations<DrillDownToEntity<T[K]>>
}

/**
 * If T is not array-like, replace it with U. If it is, replace it with same level of arrays of U.
 */
type ChangeType<T, U> = T extends Array<infer A> ? Array<ChangeType<A, U>> : U;

type PickKeysInRelation<T extends BaseEntity, R extends Relations<T>> = {
  [K in keyof T as DrillDownToEntity<T[K]> extends never ? K : (K extends keyof R ? K : never)]: K extends keyof R ? ChangeType<T[K], PickKeysInRelation<DrillDownToEntity<T[K]>, R[K]>> : T[K]
}

πŸ™ Actual behavior

Following error occurs even when exactOptionalPropertyTypes flag is set.

Type 'R[K]' does not satisfy the constraint 'Relations<DrillDownToEntity<T[K]>>'.
  Type 'R[string] | R[number] | R[symbol]' is not assignable to type 'Relations<DrillDownToEntity<T[K]>>'.
    Type 'R[string]' is not assignable to type 'Relations<DrillDownToEntity<T[K]>>'.
      Type 'Relations<DrillDownToEntity<T[string]>> | undefined' is not assignable to type 'Relations<DrillDownToEntity<T[K]>>'.
        Type 'undefined' is not assignable to type 'Relations<DrillDownToEntity<T[K]>>'.(2344)

πŸ™‚ Expected behavior

No such error to occur, since when exactOptionalPropertyTypes flag is set, R[K] cannot be undefined according to the type definition.

ℹ️ Further information

The error is gone when I select 4.5.0-beta or Nightly (which is v4.5.0-dev.20211007 as of now). However, it is gone in these versions even when the exactOptionalPropertyTypes flag is not set. If my understanding is correct, the error should actually be there when this flag is unset, hence not sure why the error is gone in these versions even with the flag is unset.

Also, the following attempt to workaround this error does not work either:

type PickKeysInRelation<T extends BaseEntity, R extends Relations<T>> = {
  [K in keyof T as DrillDownToEntity<T[K]> extends never ? K : (K extends keyof R ? K : never)]:
    K extends keyof R ?
        (R[K] extends Relations<DrillDownToEntity<T[K]>> ? ChangeType<T[K], PickKeysInRelation<DrillDownToEntity<T[K]>, R[K]>> : never) :
        T[K]
}

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions