I have the following isResult function:
export function isResult<
R extends CustomResult<string, Record<string, any>[]>,
K extends R[typeof _type]
>(result: R, type: K): result is Extract<R, { [_type]: K }> {
return result[_type] === type;
}
const users = getUsers("abc");
if (isResult(users, "user")) {
console.log(users.userProp);
} else {
console.log(users.adminProp);
}
My goal is to
- Allow auto suggestions of the second argument of isResult() (Here: “user” | “admin”)
- Make isResult() narrow the types properly (it should not show any errors)
But I can only achieve either one. The first goal (auto complete) is achived by using K extends R[typeof _type]
. And the second (narrowing properly) only works with K extends string
.
It seems that Typescript interprets K as the literal “user” when using K extends string
but still the entire union “user” | “admin” when using K extends R[typeof _type]
.
The only way I found that works with both goals is the use of K extends R[typeof _type]
and isResult(users, "user" as const)
.
I have 2 Questions:
- Why does it work without
as const
when usingK extends string
? - How can I avoid the use of
as const
while keeping the auto complete of the second argument of isResult()?