microsoft / microsoft/TypeScript

Generic constraint generates a TS2344

オープン
#36,852 コメント 0 件 リアクション 0 件 担当者 0 名 GitHub で見る

まだ誰も着手していません。

Needs Investigation
主要言語
Go
スター
111k
フォーク
14.4k
平均マージ
1日 19時間
マージ済み PR(30日)
117

説明

TypeScript Version: 3.7.x, 3.8.1, 3.9.x (next)

Search Terms: Generic constraint 2344

Code

type KeyOf<T> = keyof ((T extends any ? (k: T)=>void : never) extends ((k: infer I)=>void) ? I : never);

type Constraint<T> = KeyOf<T> extends never
  ? any
    // : KeyOf<any> extends KeyOf<T>
    // ? any
  : (
    'a' extends KeyOf<T>
      ? never
      : any
    );

type ForceConstraint<T> = T extends Constraint<T> ? T : never;

interface Interface<T extends Constraint<T>> {
  b: string;
}

type Infer<CB> = CB extends () => infer TReturn
  ? ForceConstraint<TReturn>
  : never;

type InferWithConstraint<CB> = ForceConstraint<Infer<CB>>;

type InferInterfaceFromCallback<CB> = Interface<InferWithConstraint<CB>>; // invalid => NOT OK
type InferInterfaceFromCallback1<CB> = Interface<Infer<CB>;> // invalid too => NOT OK

// just debug purpose
type A1 = Interface<unknown>;
type A2 = Interface<any>; // invalid => OK
type A3 = Interface<never>;
type A4 = Interface<undefined>;
type A5 = Interface<number>;
type A6 = Interface<string>;
type A7 = Interface<null>;
type A8 = Interface<object>;
type A9 = Interface<{}>;
type A_FAIL1 = Interface<{ a: 'b' }>; // invalid => OK
type A_FAIL2 = Interface<{ a: 'b' } | 1>; // invalid => OK

Playground Link

Expected behavior:

type InferInterfaceFromCallback<CB> = Interface<InferWithConstraint<CB>>;

Should be valid

Explanation:

So, i was trying to apply a specific constraint on a generic type.

Constraint<T> 'returns' never if T contains a property called a, else it returns any

ForceConstraint<T> tries to help typescript to know if T is valid, else it returns never

Interface<T extends Constraint<T>> forces its generic type to respect Constraint

Infer<CB> infers the return type of CB and ensures it follows Constraint

InferWithConstraint<CB> forces again Infer<CB> to be compliant with Constraint (even if it is already)

So Interface<InferWithConstraint<CB>> should be valid, sadly, typescript reports:

TS2344: Type 'ForceConstraint<Infer<CB>>' does not satisfy the constraint 'Constraint<ForceConstraint<Infer<CB>>>'.

Potentially related issues:

コントリビューションガイド

コントリビューションガイドを開く

はじめの一歩

  1. issue を最後まで読み、次にプロジェクトのコントリビューションガイドを読みます。
  2. 着手することを issue にコメントします — 二人が同じ作業をするのを防げます。
  3. リポジトリをフォークし、ブランチを切って変更します。
  4. issue 番号を参照したプルリクエストを送ります。

調査の方向性

提供された Playground Link から始め、最小限のジェネリック型の例を使って TS2344 診断を再現します。Interface<InferWithConstraint> が有効であるという想定と、報告された制約エラーを比較し、関連する Issues 31736 と 34604 を確認します。有効な型エイリアスが TS2344 を生成しなくなり、無効な例が引き続き拒否されれば完了です。

索引モデルが issue の本文から書いたものです。

評価

技術スタック
typescript
領域
compilers
issue の種類
バグ
難易度
5/5
見積もり時間
1週間以上
活発さ
停滞
明瞭さ
おおむね明確
初心者へのやさしさ
35/100

新しい issue をメールで受け取る

初心者向けの GitHub issue を短くまとめたダイジェスト。