defineProps with Typescript type always infer props to "null"
Vue version
v3.2.20
Link to minimal reproduction
Steps to reproduce
Using <script setup lang="ts>
, the defineProps<PropsType>
function does not infer correct props attributes from the Typescript type. It always generate props being null
.
- Create a Typescript type for some props. For instance:
interface PropsType {
foo: string;
bar?: number;
}
- Use this type in the
defineProps
generic type:defineProps<PropsType>()
- Take a look at the props object in the transpiled code
What is expected?
The transpiled props object should be
props: {
foo: { type: String, required: true },
bar: Number
},
What is actually happening?
This is what is generated since v3.2.20 (it's working fine before that version)
props: {
foo: null,
bar: null
},
System Info
N/A
Any additional comments?
You can switch between versions on the playground to see it's a regression from version v3.2.20.
Type verification is performed only in the development environment and not in the production environment. So the production environment type is changed to null.
However, there is still a problem with this demo. When switching to DEV, it returns an error. This is something we need to solve.(It will be fixed in the repl
via https://github.com/vuejs/repl/pull/72)
Two questions related to this issue:
- Shouldn't the production initialize to
undefined
rather thannull
? The distinction is important in some of the code I've written! - When I moved to pure Typescript description of my props, I noticed Volar in VS Code will not complain if non-optional props are missing (I also wanted required: true) to get set for variables like
foo
above. Is there a planned fix to have this behavior in the future? Do I need to submit an issue in the Volar github?
The compiler should actually not create such an output. it should create this:
props: {
msg: { type: String, required: true },
labels: { type: Array, required: false }
},
Thing is: I copied this code from the compiled output for that component when pasted into a real vite projects using the latest version of Vue.
So it seems this is a Playground problem, but not sure if related to the issue @edison1105 linked?
@LinusBorg we do not check props type in production since this commit only Boolean and Function will keep the type in prod.
const props = defineProps<{msg: string}>()
// compiled code is:
props: {
msg: null
}
so I feel this is by design.