Answer the question
In order to leave comments, you need to log in
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 literaltype MyT = Record<string, number>;
const r = f<MyT>('test');
but here the generic swears that it wants 2 arguments, and only 1 is passed. 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 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: Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question