Typescript argument type identification

49 Views Asked by At

The following code works well but I wish to rewrite it more clearly, with a Typescript idiom, if possible.

class Actions { actions: string[] }
type Argument = object | Actions;

export class GetFilesContext implements IExecutable {

   execute( args: Argument, response: ServerResponse<IncomingMessage> ): void {
      ...
      // eslint-disable-next-line no-prototype-builtins
      if( args && args.hasOwnProperty( "actions" )) {
         ctxt.actions.length = 0;
         ctxt.actions.push( ...(args as Actions).actions );
      }
      response.end( JSON.stringify( ctxt ));
   }
}

The two lines:

// eslint-disable-next-line no-prototype-builtins
if( args && args.hasOwnProperty( "actions" )) {

means "if args is defined and has an attribute actions"

How to write it?

I tried typeof and instanceof, without success.

1

There are 1 best solutions below

0
Aubin On

The correct syntax was given by pink in comments, thanks!

type Argument = object | { actions: string[] };

export class GetFilesContext implements IExecutable {

   execute( args: Argument, response: ServerResponse<IncomingMessage> ): void {
      ...
      if( args &&( 'actions' in args )) {
         ctxt.actions.push( ...args.actions );
      }
      response.end( JSON.stringify( ctxt ));
   }
}