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 expecting the behaviour above. I want to do this in a generic way so I don't want to repeat if, else statement in isSomeType function.Basically I want to convert string literal type into appropriate type based on 'type' property. My attempt was to do this:
function isSomeType<T extends Action>(x: any): x is T {
type p1 = T['type'];
return x && typeof (x.type) === p1;
}
But the message says: 'p1' only refers to a type but is used as a variable here.
Is there a way to do this?