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: pass interface as arguments of function signature

I have an interface where I define an onChange function

interface SimpleInterface {
   onChange: (fieldId: FieldId, column: number) => void;
}

I’d like to pass an interface as the arguments, something like:

interface Arguments {
  fieldId: FieldId, column: number
}

But this won’t work:

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

onChange: (Arguments) => void;

I’m getting the error ‘parameter has a nice but no type
I can do:

onChange: (arg0: Arguments) => void;

But then I only have one argument?

The reason why I’m trying to do this is because this function can take different structures of arguments, not just the one I’m presenting, so I’d like to pass a few interface as unions, something like this:

onChange: (Arguments | AnotherSetOfArguments) => void;

>Solution :

You can use rest parameters in your function, and use a union of labeled tuple types for their types, like this:

TS Playground

type FieldId = string | number;

type Params1 = [fieldId: FieldId, column: number];
type Params2 = [fieldId: FieldId];

function onChange (...params: Params1 | Params2): void {}

However, you might consider reading about function overload signatures, which can potentially provide a better developer experience in this case (depending on the way your function is designed).

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