I'm working with the isResult
function below:
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 objective is to:
- Enable auto suggestions for the second argument of
isResult
(in this case:
); and"user" | "admin"
- Ensure that
isResult
properly narrows down the types without errors;
However, I can only achieve one goal at a time. Auto complete works by using K extends R[typeof _type]
. Proper narrowing only happens when using K extends string
.
It appears that TypeScript treats K
as the literal "user"
under K extends string
, but retains the entire union
"user" | "admin"
with K extends R[typeof _type]
.
The only method I found that satisfies both goals is using K extends R[typeof _type]
along with
isResult(users, "user" as const)
.
I have two inquiries:
- Why does it work without
as const
when usingK extends string
? - How can I eliminate the need for
as const
while retaining the auto suggestion for the second argument ofisResult
?
Complete Code: https://codepen.io/web-dev-sam/pen/gOJepNa