1

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;

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

1 Comment

You're right it's working and I'll read about overload signatures thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.