Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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;
};

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading