Type errors using properties with Vue3 SFC with TypeScript

Solution 1:

well I created a new vite application using the vue-ts setup by default, and the only thing you're missing in the first example is the import of the. PropType type.

<template>
  <div>
    <button @click="onClick">{{ label }}</button>
  </div>
</template>
<script lang="ts">
import { defineComponent, PropType } from "vue";

export default defineComponent({
  name: "Test",
  props: {
    label: {
      type: String as PropType<string>,
      required: true,
    },
  },
  methods: {
    onClick() {
      console.log(this.label); // This line yields an error!
    },
  },
});
</script>

And this is the parent component (default App.vue component)

<script setup lang="ts">
// This starter template is using Vue 3 <script setup> SFCs
// Check out https://v3.vuejs.org/api/sfc-script-setup.html#sfc-script-setup
import HelloWorld from "./components/HelloWorld.vue";
</script>

<template>
  <img alt="Vue logo" src="./assets/logo.png" />
  <HelloWorld label="Hello Vue 3 + TypeScript + Vite" />
</template>

<style>
#app {
  font-family: Avenir, Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}
</style>

This is working fine for me.

Now the same example with the setup keyword in the script tag:

<template>
  <div>
    <button @click="onClick">{{ label }}</button>
  </div>
</template>

<script lang="ts" setup>
import { PropType } from "vue";
const props = defineProps({
  label: {
    type: String as PropType<string>,
    required: true,
  },
});

const onClick = () => {
  console.log(props.label); // This line yields an error!
};
</script>

It also works.

And finally using the setup method:

<template>
  <div>
    <button @click="onClick">{{ label }}</button>
  </div>
</template>

<script lang="ts">
import { defineComponent, PropType } from "vue";

export default defineComponent({
  name: "Test",
  props: {
    label: {
      type: String as PropType<string>,
      required: true,
    },
  },
  setup(props) {
    const onClick = () => {
      console.log(props.label); // This line yields an error!
    };
    return { onClick };
  },
});
</script>

Hopefully, this will solve your issue.