6

I have an object property with the following signature.

handleItem = (data: Output & { isValid: boolean }) => {}

I do not understand the & part.

Basically I trying to pass some arguments as:

handleItem (outputItem, { isValid: false })

and I receive an error

Expected 1 arguments, but got 2.'

How to pass values property? How the & is used in this instance?

5
  • It looks like & { isValid: boolean } is describing the data: Output part. This makes sense, considering there should be one argument. Commented Feb 2, 2018 at 13:39
  • Everything after the : is a type annotation. The function only takes a single object as argument. (And that object needs to contain an isValid property.) Commented Feb 2, 2018 at 13:39
  • handleItem = (data: Output, obj: { isValid: boolean }) => {} Commented Feb 2, 2018 at 13:40
  • so the isValid is optional? Commented Feb 2, 2018 at 13:40
  • not sure ,could you please provide me an example how to call this one? Commented Feb 2, 2018 at 13:41

4 Answers 4

6

handleItem takes a single argument, an object that has the properties of Output and the isValid property. You need to construct such an object. Using the spread operator is a good option:

handleItem ({ isValid: false, ...outputItem })

You can read more about intersection types here

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

1 Comment

this one does the trick thanks
3

this is called Intersection Type and it means that your param of your handleItem() method combines Output and { isValid: boolean } - will say that your parameter needs to have both types, Output and { isValid: boolean }.

Typescript & operator

so you need to call it this way:

handleItem ({ isValid: false, ...outputItem })

if you want to pass two parameters do the following:

handleItem = (data: Output, { isValid: boolean }) => {}

afterwards you can do:

handleItem (outputItem, { isValid: false })

Comments

2

& is a type intersection. Output & { isValid: boolean } means it expects something as argument that conforms both to the interface Output and { isValid: boolean }. In other words, it expects one object which has an isValid property and whatever else Output defines.

Comments

0

I think the syntax expect the property isValid of data to be boolean

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.