0

I have a type set up as follows

type StateProps = { 
    isPending: boolean,
    asyncFn: (...args: any[]) => void | null
}

I then create an initialState variable which has null for asyncFn

let initialState = {
    isPending: false,
    asyncFn: null
}

Then later in I use it in a react reducer as follows.

const [state, dispatch] = useReducer(reducer, {...initialState})

but it produces the following error

Type 'null' is not assignable to type '(...args: any[]) => void | null'

I thought that my asyncFn could be a function (with any number of args) or null if no function is supplied, as indicated by the single pipe symbol. Have I misunderstood this?

1 Answer 1

4

The type:

(...args: any[]) => void | null

is not

((...args: any[]) => void) | null

but

(...args: any[]) => (void | null)

That is, it's the type for a function which either returns null or void.

I'd put null in the first position instead, to make it clear:

asyncFn: null | (...args: any[]) => void

(or make the property optional: asyncFn?: (...args: any[]) => void)

To be type-safe, also consider using unknown instead of any.

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

1 Comment

Thanks, seems obvious now that the second set of parentheses are needed.

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.