Home > Blockchain >  Data type assignment TS Vue3
Data type assignment TS Vue3

Time:05-18

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>()

CodePudding user response:

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>()
  • Related