Permit a property if other property is present in Vue Typescript SFC

30 Views Asked by At

I want to permit a property (e.g. modelValue) of an interface if a other property (e.g. valueUrl) is present. Is this possible in TypeScript?

Following Example:

I have a MyInput.vue file where you can pass a modelValue or a valueUrl. It should not be possible to pass both modelValue and valueUrl.

<script setup lang="ts">
  import { ref } from 'vue';
  const props = defineProps<{
    label: string, 
    min?: number,
    max?: number,
    modelValue?: number, 
    valueUrl?: string,
  }>();

  const remoteValue = ref(null);
  if(props.valueUrl){
    // fetch the value from remote service
    remoteValue.value = 99;
  }
</script>

<template>
  <div>
    <label>{{label}}</label>
    <input :value="modelValue ?? remoteValue">
  </div>
</template>

so for example in the last row an error should occur:

<script setup lang="ts">
import { ref } from 'vue';
import MyInput from './MyInput.vue';

const val = ref(1);
</script>

<template>
  <MyInput label="Valid input via value" v-model="val" />
  <MyInput label="Via input via value url" value-url="https://myUrl.com/myValue"/>
  <MyInput label="This should not be possible" v-model="val" value-url="https://myUrl.com/myValue"/>
</template>

You can try this code here. I'm building a Vue-Component-Library so it would be nice if such an error occurs while compiling and not in runtime.

0

There are 0 best solutions below