microsoft / microsoft/TypeScript
Generic arguments gets casted as "unknown" when used as function argument
Dieses Issue hat noch niemand übernommen.
- Vorherrschende Sprache
- Go
- Sterne
- 111k
- Forks
- 14.4k
- Ø Merge
- 1 T. 19 Std.
- Gemergte PRs (30 T.)
- 117
Beschreibung
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.
Beitragsleitfaden
Erste Schritte
- Lies das ganze Issue und danach den Beitragsleitfaden des Projekts.
- Schreib ins Issue, dass du es übernimmst — das erspart doppelte Arbeit.
- Forke das Repository und arbeite in einem Branch.
- Öffne einen Pull Request, der die Issue-Nummer nennt.
Rechercherichtung
Beginne mit dem verknüpften TypeScript Playground und reproduziere das Verhalten rund um buildSchema, FormSchema und InferSharedStoreData. Verfolge, warum der Parametertyp von dataWithArg zu InferSharedStoreData wird; die Aufgabe ist abgeschlossen, wenn params als das aus dem Store des Schemas abgeleitete StoreData inferiert wird, während die anderen Eigenschaften weiterhin typgeprüft werden.
Vom Indexierungsmodell aus dem Issue-Text verfasst.
Bewertung
- Tech-Stack
- typescript
- Bereich
- compilers
- Issue-Typ
- Bug
- Schwierigkeit
- 4/5
- Geschätzter Aufwand
- 3-5 Tage
- Aktivitätsstatus
- Veraltet
- Klarheit
- Größtenteils klar
- Anfängerfreundlichkeit
- 35/100