Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How to properly type props in TS #1494

Closed
whu-luojian opened this issue Jul 3, 2020 · 1 comment
Closed

How to properly type props in TS #1494

whu-luojian opened this issue Jul 3, 2020 · 1 comment

Comments

@whu-luojian
Copy link

Version

3.0.0-beta.18

Reproduction link

https://github.com/whu-luojian/webpack-vue3

Steps to reproduce

<script lang="ts">
import { defineComponent, ref } from 'vue'

type TodoItem = {
  id: number
  text: string
  completed: boolean
}

type Props = {
  todo: TodoItem
}

export default defineComponent({
  name: 'TodoItem',
  props: {
    todo: {
      type: Object,
      required: true
    }
  },
  setup(props: Props) {
    console.log(JSON.stringify(props, null, 2))
    const count = ref(0)
    return {
      count
    }
  }
})
</script>

What is expected?

it will work correctly or there are any better solution to properly type props in TS

What is actually happening?

setup function throw a ts error by Vetur:
No overload matches this call.
The last overload gave the following error.
Type '(this: void, props: Props) => { count: Ref; }' is not assignable to type '(this: void, props: Readonly<{ todo: { [key: string]: any; }; } & {}>, ctx: SetupContext<Record<string, any>>) => void | RenderFunction | { ...; }'.
Types of parameters 'props' and 'props' are incompatible.
Type 'Readonly<{ todo: { [key: string]: any; }; } & {}>' is not assignable to type 'Props'.
Types of property 'todo' are incompatible.
Type '{ [key: string]: any; }' is missing the following properties from type 'TodoItem': id, text, completedVetur(2769)


Related issues:
#1155
#1114

@HcySunYang
Copy link
Member

Just use the PropType, and remove type annotation on setup(props: Props):

export default defineComponent({
  name: 'TodoItem',
  props: {
    todo: {
      type: Object as PropType<TodoItem>,
      required: true
    }
  },
  setup(props) {
    console.log(JSON.stringify(props, null, 2))
    const count = ref(0)
    return {
      count
    }
  }
})

@posva posva closed this as completed Jul 3, 2020
@github-actions github-actions bot locked and limited conversation to collaborators Nov 10, 2023
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants