D
D
Dmitry Belyaev2020-03-27 10:26:41
typescript
Dmitry Belyaev, 2020-03-27 10:26:41

Is it possible to force type inference for a generic part?

Hello everyone, the main question in the subject.

I sketched a conditional example of what I want to do:

type SomeComplicatedType = any; // здесь тоже сложный тип, но к сути вопроса он отношения не имеет
type BaseType = Record<string, SomeComplicatedType>;
type ResultType<T extends BaseType, K extends keyof T> = {t: T; k: K}; // тоже упростил для примера
function f<T extends BaseType, K extends keyof T>(key: K): ResultType<T, K> {
    /* ... */
    return {k: key, t: {} as T};
}
so, I want T to be directly set by the user, and K is derived from the argument and be a specific literal
type MyT = Record<string, number>;
const r = f<MyT>('test');
but here the generic swears that it wants 2 arguments, and only 1 is passed.

So, what I tried:
1. if you make such a call: K is perfectly calculated into a specific literal type 'test', but T is output as BaseType, which does not suit 2. tried to determine default type:const r = f('test');
function f<T extends BaseType, K extends keyof T = keyof T>(key: K): ResultType<T, K>

type MyT = Record<string, number>;
const r = f<MyT>('test');
so K rolls down to all MyT keys, which is also not suitable
3. there was another attempt:
function f<T extends BaseType, K extends keyof T = (infer KK extends keyof T ? KK : keyof T)>(key: K): ResultType<T, K>

type MyT = Record<string, number>;
const r = f<MyT>('test');
and although it seems to describe exactly what I want, ts swears at infer here:
"infer" declarations are only allowed in the "extends" clause of a conditional type.ts(1338)

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Aetae, 2020-04-09
@bingo347

You can't, alas. There are many requests on github to file this, but so far (v3.8) there is not much hope.
If you look around there on cross-references, you can find different (ugly) workarounds for specific cases, but just the way you want - it won't work.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question