Vue 3 defineProps with Types and ComponentObjectPropsOptions (like default or validator)

Viewed 5650

From within a setup method, using defineProps I can use

const props = defineProps<{tabs: Tab[]}> = ()

which allows me to have the type Tab[] on props.tabs

however, if I want to specify ComponentObjectPropsOptions, I believe the syntax is

const props = defineProps = ({
  type: Array, //can not use Tab[] here
  required: true,
  validator: ...
})

but with that syntax I lose my type on props.tabs :(

3 Answers

Nuxt3, setup, lang=ts

import {ComponentObjectPropsOptions} from "vue";

interface Props {
  foo: string
  bar?: number
}

const props = defineProps<ComponentObjectPropsOptions<Props>>({
  foo: {
    type: String, 
    required: true,
    validator(value: unknown): boolean {
      return true
    }
  },
  bar: Number
})

Vue3 (Vite), setup, lang-ts

Thanks @Daniel I had to augment code from your answer to be valid in my environment.

  1. import type instead of just import
  2. export interface Props
import type { ComponentObjectPropsOptions } from "vue";

export interface Props {
    foo: string
    bar?: number
}

const props = defineProps<ComponentObjectPropsOptions<Props>>({
    foo: {
        type: String,
        required: true,
        validator(value: unknown): boolean {
            return true
        }
    },
    bar: Number
})
Related