microsoft / microsoft/TypeScript

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

Open
#53,695 2 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Needs More Info
Dominant language
Go
Stars
111k
Forks
14.3k
Avg merge
1d 19h
Merged PRs (30d)
117

Description

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.

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start with the linked TypeScript Playground and reproduce the behavior around buildSchema, FormSchema, and InferSharedStoreData. Trace why the dataWithArg params type becomes InferSharedStoreData; done means params is inferred as the StoreData derived from the schema's store while the other properties continue to type-check.

Written by the indexing model from the issue text.

Assessment

Tech stack
typescript
Domain
compilers
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.