Skip to content

Using this-type with intersection type makes it possible to simulate HKT  #40928

Closed
@ENvironmentSet

Description

@ENvironmentSet

TypeScript Version: Lastly tested in v4.1.0-dev20201003, but this has been existing at least since v3.8

Search Terms: this-type, this type, intersection, HKT, higher kinded type

Code

export interface HKT {
  param: unknown;
  result: unknown;
}

interface NotHKT extends HKT {
  result: this['param'] extends true ? false : true;
}

interface FstHKT extends HKT {
  result: this['param'] extends [infer A, infer _] ? A : never;
}

interface ArrayHKT extends HKT {
  result: Array<this['param']>;
}

export type Apply<f extends HKT, x>
  = (f & { param: x })['result'];

type Test1 = Apply<NotHKT, true> // be deducedd to `false`
type Test2 = Apply<FstHKT, [string, boolean]> // be deduced to `string`
type Test3 = Apply<ArrayHKT, number> // be deduced to `number[]`

Expected behavior: I expected that reduction of this type doesn't depends on type that is intersected with.

Actual behavior: reduction of this type depends on type that is intersected with.

The actual behavior makes sense to me(at least). It's not hard to accept its behavior. However, It looks like unintended behavior or bug (just like recursive conditional type before) so that I can't certain it's okay to use this. Is this idea safe to use?

Playground Link

Metadata

Metadata

Assignees

No one assigned

    Labels

    QuestionAn issue which isn't directly actionable in code

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions