Search code examples
typescriptaws-sdk-js

AWS SDK with Typescript


I am new to using typescript @types files. I have installed aws-sdk and @types/aws-sdk. I am trying to call list open workflows in swf. The first parameter is a "ListOpenWorkflowExcusionsInput" which I see the type file declared as an interface. Do I really need to implement this interface or am I missing something?

import {SWF} from "aws-sdk"
import {ListOpenWorkflowExecutionsInput} from 'aws-sdk/clients/swf'; 
let swf:SWF = new SWF();
let params:ListOpenWorkflowExecutionsInput = new ListOpenWorkflowExecutionsInputClass();

params.domain = "domain";
//etc...
swf.listOpenWorkflowExecutions(params,function(e,d){
     console.log(e);
     console.log(d);
});

Then I needed to define ListOpenWorkflowExecutionsInputClass.

export class ListOpenWorkflowExecutionsInputClass implements ListOpenWorkflowExecutionsInput{
    domain: SWF.DomainName;
    startTimeFilter: SWF.ExecutionTimeFilter;
    typeFilter: SWF.WorkflowTypeFilter;
    tagFilter: SWF.TagFilter;
    nextPageToken: SWF.PageToken;
    maximumPageSize: SWF.PageSize;
    reverseOrder: SWF.ReverseOrder;
    executionFilter: SWF.WorkflowExecutionFilter;
}

Solution

  • Since TypeScript uses structural typing, you can just create an object literal with fields that are required in the interface and pass it as the params, no need to create a class and implement the interface.

    In your case, since you need to provide at least values for domain and startTimeFilter, which are the only required values according to the definition file https://github.com/aws/aws-sdk-js/blob/master/clients/swf.d.ts, you can write:

    const params = {
        domain: ... // your value
        startTimeFilter: ... // your value 
    }
    

    This is a very common pattern in TypeScript. You have interfaces that define the type, and you create object literals that correspond to these interfaces and pass them around. This works because TypeScript has structural typing, i.e., if an object has the properties of a type, it is assignable to that type, without needing to explicitly implement that type.