Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Define function arguments as object in TypeScript

Rather than calling functions where the arguments are passed individually, I prefer to pass them as an object so that the order is not important.

For example,

const sum = ({ arg1, arg2, arg3 }) => arg1 + arg2 + arg3;

Now I'm migrating some code that I have across, to Typescript and I am unsure how I am supposed to define the interface for such a function.

I've tried something like this and it doesn't work:

Enter image description here

Any clues?

like image 335
oldo.nicho Avatar asked Apr 24 '26 07:04

oldo.nicho


1 Answers

Use:

interface InputObj {
    arg1: number;
    arg2: number;
    arg3: number;
}

interface ExampleProps {
    sum: (input: InputObj) => number
}

Or inline:

interface ExampleProps {
  sum: (
    input: {
      arg1: number;
      arg2: number;
      arg3: number;
    }
  ) => number;
}

But depending on your use case you may not need to define ExampleProps. Here is your sum function without the arbitrary input object name:

const sum = ({
  arg1,
  arg2,
  arg3
}: {
  arg1: number;
  arg2: number;
  arg3: number;
}) => arg1 + arg2 + arg3;
like image 190
automasean Avatar answered Apr 26 '26 20:04

automasean



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!