export interface Action{
type: string;
}
export interface LoadTodos {
type: "LOAD_TODOS_ACTION"
}
export interface AddTodo {
type: "ADD_TODO_ACTION",
todo: Todo
}
export type KnownAction = LoadTodos | LoadTodosSuccess | AddTodo;
function isSomeType<T extends KnownAction>(x: any): x is T {
return x && typeof (x.type) === "LOAD_TODOS_ACTION";
}
let knownAction: actions.KnownAction = { type: "LOAD_TODOS_ACTION" };
if (isSomeType(knownAction)) {
let loadTodosAction = knownAction; // load Todos type
}
I'm hoping for the desired outcome as described above. To avoid repeating if-else statements within the isSomeType function, I aim to achieve this in a more generic manner. Essentially, my goal is to convert a string literal type into the corresponding type based on the 'type' property. My initial approach was:
function isSomeType<T extends Action>(x: any): x is T {
type p1 = T['type'];
return x && typeof (x.type) === p1;
}
However, an error message indicates that 'p1' is used only as a type and not as a variable. Is there a method to accomplish this task?