microsoft / microsoft/TypeScript

Generic arguments gets casted as "unknown" when used as function argument

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

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

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

説明

Typescript version : 5.0.3 (But found on all versions I tested)

Search terms : generic type as function argument unknown

⏯ Playground Link

Playground link with relevant code

💻 Code

Here are the two main generics involved in my case :

type FormSchema<
  StoreKey extends string,
  StoreData extends Record<string, unknown>
> = {
  store: { key: StoreKey; value: () => unknown }[];
  fields: Array<{
    key: string;
    data: StoreData;
    dataWithoutArg: () => StoreData;
    dataWithArg: (params: StoreData) => StoreData;
  }>;
};

type InferSharedStoreData<Store extends { key: string; value: () => unknown }[]> = {
  [K in Store[number] as K["key"]]: Awaited<ReturnType<K["value"]>>;
}

And here's the actual function that casts these :

function buildSchema<
  TSchema extends FormSchema<StoreKey, StoreData>,
  StoreKey extends string,
  StoreData extends Record<string, unknown> = InferSharedStoreData<
    TSchema["store"]
  >
>(schema: TSchema) {
  return schema as TSchema
}
🙁 Actual behavior

The "params" argument of the "dataWithArg" sub-property of "fields" is being typed as InferSharedStoreData, which means the "store" property type of the schema passed as argument of buildSchema is unavailable in the context of the function argument.

the StoreData type is being properly inferred for every other property it's assigned to, except on the case where it is used as a function argument.

🙂 Expected behavior

The function argument "params" should be inferred as StoreData, which itself is InferSharedStoreData<schema['store']>. A complete example is set-up on the playground link above.

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

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

はじめの一歩

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

調査の方向性

リンクされている TypeScript Playground から始め、buildSchema、FormSchema、InferSharedStoreData 周辺の挙動を再現します。dataWithArg の params 型が InferSharedStoreData になる理由を追跡します。params がスキーマの store から導出された StoreData として推論され、他のプロパティは引き続き型チェックされれば完了です。

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

評価

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

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

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