I'm using vue3 with typescript, and I'm using composition API.
export default {
setup(props, context) {
},
};
This throws an error as follows
Failed to compile.
src/components/LoginForm.vue:20:11
TS7006: Parameter 'props' implicitly has an 'any' type.
18 |
19 | export default {
> 20 | setup(props, context) {
| ^^^^^
I know this can be fixed by making props
, context
of type any, but that will defeat the purpose of TypeScript.
VS Code intellisense showing me the following type, but I'm not able to find the module from these type are exported.
setup?: ((this: void, props: {}, ctx: SetupContext<EmitsOptions>) => void | RenderFunction
What is the correct Type for the setup
function, and from where it is exported ?.
While Vue does support TypeScript usage with Options API, it is recommended to use Vue with TypeScript via Composition API as it offers simpler, more efficient and more robust type inference. Type inference for props in Options API requires wrapping the component with defineComponent ().
It is still possible to use plain Javascript with Vue 3, if you are not keen on Typescript. This section of my Vue 3 guide explains how to install and set up Typescript with a Vue 3 installation.
If you have Vetur currently installed, make sure to disable it in Vue 3 projects. TypeScript Vue Plugin is also needed to get type support for *.vue imports in TS files. WebStorm also provides out-of-the-box support for both TypeScript and Vue. Other JetBrains IDEs support them too, either out of the box or via a free plugin.
At the same time, plain TS files are still handled by VSCode's built-in TS language service, which is why we need TypeScript Vue Plugin to support Vue SFC imports in TS files. This default setup works, but for each project we are running two TS language service instances: one from Volar, one from VSCode's built-in service.
The props can not be inferred because you forget to use defineComponent
method to create your component. To resolve this issue and let props to be infrared by Vue you need to wrap your whole object which you are exporting in defineComponent
method.
More about defineComponent
The <script lang="ts">
part of example Vue 3 composition API component should look like that:
export default defineComponent({
name: "PersonComponent",
props: {
firstName: {
type: String,
required: true
},
lastName: {
type: String,
required: true
},
age: {
type: Number,
required: true
}
},
setup(props) {
const firstName = props.firstName;
const lastName = props.lastName;
const age = props.age;
return {
firstName,
lastName,
age
};
}
})
For more complexd types such as interfaces you need to use
Object as PropType<T>
(Object as PropType<IconProps>
). More aboutPropType<T>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With