MistyK
MistyK

Reputation: 6232

How to convert string into string literal type in Typescript?

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.

Upvotes: 1

Views: 702

Answers (1)

Nitzan Tomer
Nitzan Tomer

Reputation: 164367

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
}

Upvotes: 1

Related Questions