Composition-api: prop with `required: true` have type undefined

Created on 29 Aug 2019  ·  9Comments  ·  Source: vuejs/composition-api

Description

As Vue handle required validation and throws an error if a component is missing a required prop, the resulting type of a requiredprop shouldn't be "possibly" undefined.

Markup

import { createComponent } from '@vue/composition-api'

export default createComponent({
  props: {
    defaultNumber: {
      type: Number,
      default: 2
    },
    requiredNumber: {
      type: Number,
      required: true
    }
  },
  setup ({ defaultNumber, requiredNumber }) {
    return {
      defaultNumber,
      requiredNumber
    }
  }
})

Prop with default value 👍

image

Prop required

image
requiredNumber is expected to be of type number, not number | undefined

Notes

I guess there's something wrong around https://github.com/vuejs/composition-api/blob/master/src/component/componentProps.ts#L20

Workaround

@lbssousa mentionned casting props to const and it works.
But I think it shouldn't be needed and there is something to fix around types.

documentation

Most helpful comment

In fact, we can get rid of as const.

All 9 comments

You may need to put as const at the end of props: { ... }

@lbssousa Nice catch ! but isn't there an issue around the types (see Notes section) that would make it work without having casting to const ?

Also, I'm wondering why we don't have Intellisense for type, default, required and validator like we used to with Vue.extend :
image

@kevinmarrec Why did it not work for me? 🤔

image

@liximomo Which installed version of TypeScript have you in the workspace of this snippet ?

And about the original creation of this issue, is there anything we can fix instead of casting props to const ?

I mean it's working for props with default values so I still think there's some fix to do around types.

@kevinmarrec The as const is required. We need to use as const to narrow down the inferred type from boolean to true.

In fact, we can get rid of as const.

Nice :)

In case anyone else like me ends up here from a web search wondering about props with an inferred any, or missing intellisense for createComponent like mentioned above, note the readme states:

This plugin requires TypeScript version >3.5.1. If you are using vetur, make sure to set vetur.useWorkspaceDependencies to true.

https://github.com/vuejs/composition-api#typescript

Upgrading our TypeScript fixed the intellisense and type inference.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

TooBug picture TooBug  ·  6Comments

lixpng picture lixpng  ·  6Comments

spaceemotion picture spaceemotion  ·  6Comments

lephuongbg picture lephuongbg  ·  3Comments

SeregPie picture SeregPie  ·  6Comments