Home > Enterprise >  Typescript make a function in an object returning the type of an associated key of an interface
Typescript make a function in an object returning the type of an associated key of an interface

Time:12-24

I was wondering if there is a way to do that in typescript. Let's say i have a this interface:

interface Transaction {
   amount: number;
   order_date: Date;
   id: string;
}

I would like to create a type called Mapper that would map each key of an json received for an external API to my own interface, for example:

const ExternalAPIMapper: Mapper = {
   amount: (raw_transaction) => raw_transaction.sale_amount,
   order_date: ({ transaction_date }) => dayjs(transaction_date, 'YYYY.MM.DD').toDate()),
   id: ({ transaction_id }) => transaction_id
}

I've created the following type:

type Mapper = Record<keyof Transaction, ((t: any) => any)>

But the problem with this type is that my function can return any type. I would like the function to be typed to return the type associated with the key. Is it possible ?

If it works, I could map a JSON of any external API just with a mapper and this function :

const mapNetworkTransaction = (
  object: Record<string, string>,
  mapper: Mapper,
): Transaction => {
  const txn = { };
  for (let i = 0; i < txnFields.length; i  ) {
    const txnField = txnFields[i];
    const accessor = mapper[txnField];
    if (accessor) {
       txn[txnField] = accessor(object);
    }
  }
  return txn;
};

CodePudding user response:

You should use a mapped type instead.

type Mapper = {
  [K in keyof Transaction]: (t: any) => Transaction[K]
}

This produces a type which looks like this:

type Mapper = {
    amount: (t: any) => number;
    order_date: (t: any) => Date;
    id: (t: any) => string;
}

Playground

  • Related