0

In my components, i want to use <script setup lang="ts"> . But I ran into a type problem. Example of a normal component <script lang="ts">:

props: {
    modelValue: {
      type: [Boolean, String, Number, Array as () => Array<string | number>],
      required: true,
    },
    value: {
      type: [Boolean, String, Number, Array as () => Array<string>],
      default: "",
    },
    label: {
      type: [String, Number],
      default: "",
    },
}

Component <script setup lang="ts">. How to correctly set such types in the interface ?

interface Props {
  modelValue: [Boolean, String, Number, Array as () => Array<string | number>]
  value: [Boolean, String, Number, Array as () => Array<string>]
  label: [String, Number]
}
const props = defineProps<Props>()

1 Answer 1

1

To combine types in TypeScript, use union types. For instance, this constructor array:

[Boolean, String, Number, Array as () => Array<string | number>]

...becomes this in type in TypeScript:

boolean | string | number | (string | number)[]

So, the equivalent TypeScript interface of your original code would be:

interface Props {
  modelValue: boolean | string | number | (string | number)[]
  value: boolean | string | number | string[]
  label: string | number
}
const props = defineProps<Props>()

To set default values for the props, use withDefaults():

const props = withDefaults(defineProps<Props>(), {
  value: '',
  label: '',
})

...or use object destructuring with default values:

const {
  modelValue = '',
  value = '',
  label = '',
} = defineProps<Props>()
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.