1
export interface LoadTodos {
  type: "LOAD_TODOS_ACTION"
}

export interface AddTodo {
  type: "ADD_TODO_ACTION",
  todo: Todo
}

export type KnownAction = LoadTodos| AddTodo;

currently I'm doing this:

  CallAction({ type: "LOAD_TODOS_ACTION" });

I want to do this:

CallAction("LOAD_TODOS_ACTION");

or ideally:

CallAction<LoadTodos>();

How should I implement CallAction? Is it even possible?

function CallAction<T extends KnownAction>()
{
   type P1 = T["type"];
 doSomethingWithAction({type:T.type}); // type property is an instance property so cannot be retrieved obviously

//or 

 type P1 = T["type"];
 doSomethingWithAction({type:P1}); // P1 is a type not string


    }

LoadTodos contains type: "LOAD_TODOS_ACTION" so there should be a way to get one from the other.

1 Answer 1

1

If I understand you correctly then:

type ActionType = "LOAD_TODOS_ACTION" | "ADD_TODO_ACTION";

interface Action {
    type: ActionType;
}

interface LoadTodos extends Action {
    type: "LOAD_TODOS_ACTION"
}

interface AddTodo extends Action {
    type: "ADD_TODO_ACTION",
    todo: Todo
}

function CallAction(type: ActionType) {
    // whatever
}

Or:

function CallAction<T extends Action>(action: T) {
    // whatever
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.