Subscribe on changes!

Typescript vue 3 setting props via variable gets optional properties of props that has required attributes

avatar
Mar 5th 2021

Version

3.0.7

Reproduction link

https://github.com/Lilja/vue3-props-typing-repro

Steps to reproduce

git clone https://github.com/Lilja/vue3-props-typing-repro && cd vue3-props-typing-repro && yarn build

What is expected?

const msg: string = props.msg to work, vue wants it to be optional.

What is actually happening?

const msg: string = props.msg doesn't work.

msg: string | undefined since props.msg is undefined.


It has to do probably because required: true is not parsed as a required: true boolean literal, but required: boolean. To solve, modify the code:

type HelloWorldPropsType = {
    msg: {
        type: PropType<string>,
        required: true
    }
}
const ComponentProps: HelloWorldPropsType = {
    msg: {
        type: String as PropType<string>,
        required: true
    }
}

I've created an issue with the vetur project and they refered here.

Direct link to the relevant component

avatar
Mar 5th 2021

You need to write

const ComponentProps = {
    msg: {
        type: String as PropType<string>,
        required: true
    }
} as const

since you are declaring them outside of defineComponent()