Home > Enterprise >  Typescript: pass interface as arguments of function signature
Typescript: pass interface as arguments of function signature

Time:09-26

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:

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;

CodePudding user response:

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).

  • Related