Subscribe on changes!

Support nullable Function props

avatar
May 11th 2021

Version

3.1.0-beta.2

Reproduction link

https://github.com/AverageHelper/prop-type-function-or-null

Steps to reproduce

  1. Install the latest version of Vetur for VSCode (v0.33.1)
  2. Install dependencies (npm install)
  3. Reload the VSCode window
  4. Open the src/Test.vue file

What is expected?

Line 16 should pass type checking

What is actually happening?

Vetur reports an error on line 16 where the Function type is augmented.


This issue only occurs when the PropType annotation contains null. Vetur takes a normal function signature there just fine.

Since other prop types allow being augmented with null in this manner, and Vue has supported adding function signatures to props since #9733, I'm fairly certain this syntax should work.

Nullable function props are useful over events in the case where a component should behave differently based on the existence of a callback function. For example, a component may in some contexts be interactive, perhaps indicating in its UI that it is interactive, and calling a callback function passed by its parent component. In other contexts, the same component may only display data, but formatted in the same manner as the interactive version. I don't know a way to have a component check that its parent component handles an event, so function props have been a good way for us to make that check.

avatar
May 12th 2021

It's not really a Vue problem or a Vetur problem, but just how TS works.

PropType is defined as a constructor that returns the actual prop type. Function never returns null, so TS doesn't allow it.

Technically speaking, TS is stricter than Vue's runtime semantics because Vue does allow null values for optional props. To get around this you'll just have to do a force cast with Function as any as PropType<OnSelectCallback | null>. I don't think there is a way for Vue to make this magically work.