Home > Software engineering >  Vue typescript props is dependent on another prop
Vue typescript props is dependent on another prop

Time:01-05

Using <script setup lang="ts">, how can I define a property that is dependent from another property?

Example: I want to require a variable if another variable is present.

I tried doing defineProps<Props | PropsA>(), but an error occurred. It says that [@vue/compiler-sfc] type argument passed to defineProps() must be a literal type, or a reference to an interface or literal type.

CodePudding user response:

You would use this syntax:

const props = defineProps<
myRequiredPropName: Props | PropsA
myOptionalPropName?: Props | PropsA
>()

// in your script/setup: props.myRequiredPropName
// in your template: myRequiredPropName

You cannot conditionally require a property and have the typescript compiler catch it.

CodePudding user response:

Imported types and complex ones are not supported for argument declaration type.

As of now, the type declaration argument must be one of the following to ensure correct static analysis:

  • A type literal
  • A reference to an interface or a type literal in the same file

But you can use PropType utility :

<script lang="ts" setup>

  const props = defineProps({
       propName:{
          type: Object as PropType<Type1 | Type2>
      }

   });
</script>
  • Related