David Faizulaev
David Faizulaev

Reputation: 5721

Typescript - defining a type which is based on other type while specifying a specific field value

I'm writing a Graphql API and defining types in typescript. I would like these types to be enforced as they describe the API input.

I would like to know if I can do something like this:

enum ActionType {
  CREATE = 'create',
  DELETE = 'delete',
}

interface BaseAction {
  actionType: ActionType;
};

type DeleteAction = BaseAction & {  
  actionType: ActionType.DELETE;
  id: string;
};

type CreateAction = BaseAction & {  
  actionType: ActionType.CREATE
  data: string;
  secArg: number;
};

Where I have an interface BaseAction and other types inherit/implement it while specifying the relevant action type.

Is this something which is preferable to do? or there another way on achieving such a definition?

Thanks in advance.

Upvotes: 0

Views: 46

Answers (2)

Majid M.
Majid M.

Reputation: 4954

If you want to code automatically detect the type of actions when you create for instance a DeleteAction, you can change your types to classes and implement the BaseAction interface. Something like this :

enum ActionType {
  CREATE = 'create',
  DELETE = 'delete',
}

interface BaseAction {
  actionType: ActionType;
};

class DeleteActionClass implements BaseAction {
   public readonly actionType: ActionType;
   public id:string;
   constructor(id:string){
     this.actionType = ActionType.DELETE;
     this.id = id;
 }
 }

 const myfunc = (deleteAction:DeleteActionClass)=>{
   console.log(deleteAction.actionType)
 }

 const deleteAction : DeleteActionClass =  new DeleteActionClass('5');
 myfunc(deleteAction) // it logs 'delete' in console

Upvotes: 0

Snehal Baghel
Snehal Baghel

Reputation: 317

I think this is what you're looking for (What you are doing should work too). You may also benefit from exhaustive checking in your reduced function with a pattern like this.

Upvotes: 1

Related Questions