Answer the question
In order to leave comments, you need to log in
How to make TS work with type groups?
There is a function:
const f = (someObj: T1 | T2, someEnum: typeof E1 | typeof E2): string => {
return someObj[someEnum.a];
};
T1 + E1
, or T2 + E2
. someObj[someEnum.a]
an error (ts(7053)) comes out in all the options that I tried (in particular, overloading and arguments in the form of an object). Element implicitly has an 'any' type because expression of type 'E1.a | E2.a' can't be used to index type 'T1 | T2'.
Property '[E1.a]' does not exist on type 'T1 | T2'.(7053)
enum E1 {
a = 'a1',
}
enum E2 {
a = 'a2',
}
type T1 = {
[key in E1]: string;
};
type T2 = {
[key in E2]: string;
};
{
const f = (someObj: T1 | T2, someEnum: typeof E1 | typeof E2): string => {
return someObj[someEnum.a]; // ts(7053)
};
}
{
function f(someObj: T1, someEnum: typeof E1): string;
function f(someObj: T2, someEnum: typeof E2): string;
function f(someObj: T1 | T2, someEnum: typeof E1 | typeof E2): string {
return someObj[someEnum.a]; // ts(7053)
}
}
{
type TT =
| { someObj: T1; someEnum: typeof E1 }
| { someObj: T2; someEnum: typeof E2 };
const f = (tt: TT): string => {
return tt.someObj[tt.someEnum.a]; // ts(7053)
};
}
T1 + E2
or T2 + E1
? T1/T2
can be empty.
Answer the question
In order to leave comments, you need to log in
Judging by the activity, there is no adequate solution. I had to resort to minimal crutches:
function f(someObj: T1, someEnum: typeof E1): string;
function f(someObj: T2, someEnum: typeof E2): string;
function f(someObj: T1 | T2, someEnum: typeof E1 | typeof E2): string {
const typedSomeObj = someObj as T1 & T2;
return typedSomeObj[someEnum.a];
}
It can be like this:
function f<X extends { [index: string]: string }>(someObj: X, someEnum: keyof X): string {
return someObj[someEnum];
}
const f = <T extends T1 | T2>(someObj: T, someEnum: T extends T1 ? typeof E1 : typeof E2) => {
return (someObj as T1 & T2)[someEnum.a];
};
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question