pmiranda
pmiranda

Reputation: 8470

TypeScript problem with type on returned value

I'm getting this tslint error:

TS2322: Type 'ItemList | undefined' is not assignable to type 'Transaction<any, any, any>[]'.   Type 'undefined' is not assignable to type 'Transaction<any, any, any>[]'.

I have this code:

import { Transaction } from 'types';
import { DocumentClient as DynamoDBDocumentClient } from 'aws-sdk/clients/dynamodb';

export default async function getMyTransactions (
  _root: any,
  args: null,
): Promise<Array<Transaction<any, any, any>>> {

    //some code for query and other stuff

  const { Items } = await DocumentClient.getInstance().query(query).promise();
  console.log('Items', Items);

  return Items;
}

In the console.log(Items) I get something like this:

[
  {
    id: '123',
    commissions: {
      cc: 500,
      total: 1337
    },
    createdAt: '2001-02-03T04:05:06+07',
]

Transaction type is this one:

// I wont put the whole code, but those TF, TV, TC are used on other types not listed here
export interface Transaction<TF, TV, TC> {
  id: string;
  commissions: Commissions;
  createdAt: string;
}

So, in the beginning of my function I declare that it will return: Promise<Array<Transaction<any, any, any>>>

So Items is actually an array of Transaction type object.

Why I'm getting the error?

Upvotes: 1

Views: 1669

Answers (1)

Poul Kruijt
Poul Kruijt

Reputation: 71961

As you can see in the typings the Items property can be undefined, because you are using the strict setting in your tsconfig.json this will result in an error. So a simple fix is to always return an array:

export default async function getMyTransactions (
  _root: any,
  args: null,
): Promise<Array<Transaction<any, any, any>>> {
  // ...
  const { Items } = await DocumentClient.getInstance().query(query).promise();
 
  return Items || [];
}

Or you have to update your return typing to reflect what Items can be, and you should handle this undefined at the consumer of your method:

Promise<Array<Transaction<any, any, any>> | undefined>

Unfortunately the typings of dynamodb do not have any generics when you are querying the data. I can assume you will have to do the following to make it work:

export interface Transaction<TF, TV, TC> extends AttributeMap {
  id: string;
  commissions: Commissions;
  createdAt: string;
}

and perhaps you have to specifically type cast it, but not sure about that:

const { Items } = await DocumentClient.getInstance().query(query).promise();
 
return Items || [] as Transaction<any, any, any>[];

Upvotes: 1

Related Questions