Allow me to present an example to demonstrate my current objective.
const v1: { type: "S"; payload: string } = { type: "S", payload: "test" };
const v2: { type: "N"; payload: number } = { type: "N", payload: 123 };
type Actions = typeof v1 | typeof v2;
const findByType = <A extends Actions>(type: A["type"]) => (
action: Actions
): action is A => action.type === type;
const filterWithBothNameAndType = [v1, v2].filter(findByType<typeof v1>("S"));
console.log(filterWithBothNameAndType[0].payload.trim());
const findByTypeDoesntWork = <A extends Actions, T extends A["type"]>(type: T) => (
action: Actions
): action is A => action.type === type;
const filterWithJustType = [v1, v2].filter(findByTypeDoesntWork("S"));
console.log(filterWithJustType[0].payload.trim());
I have a function called findByType
with correct type information, and another function named filterWithJustType
that has an API I prefer, but it loses important type data. My goal is to have the API simply as filter("S")
without needing to pass generic types. As of now, it seems like this approach only works with classes and instanceof
, yet I aim to make it compatible with plain objects.