The relationship between Vue TypeScript props is influenced by the presence of another prop

Is there a way to define a property in

<script setup lang="ts">
that depends on another property?

For instance, how can I require a variable only if another variable is present?

I attempted using

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

Answer №1

To implement this, follow the syntax below:

const properties = defineProperties<
requiredProperty: Properties | PropertyA,
optionalProperty?: Properties | PropertyA
>()

// For script/setup usage: properties.requiredProperty
// For template usage: requiredProperty

It is not possible to conditionally require a property and have it detected by the TypeScript compiler.

Answer №2

Argument declaration type does not support imported types or complex ones.

Currently, the argument type declaration must be limited to the following for accurate static analysis:

  • A literal type
  • An interface reference or a literal type within the same file

However, you can utilize the PropType utility :

<script lang="ts" setup>

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

   });
</script>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to evaluate typing into an input field?

My objective is to test the 'typing' functionality in an input element. The aim is to insert a value into the input element, verify that its binding successfully captures the value, and observe the entered value within the input element. Below i ...

TypeScript is unable to detect the .sequelizerc configuration file

I have a file called .sequelizerc which contains the following configuration: const path = require('path'); module.exports = { config: path.resolve('.', 'src/config/sequelizeCLIConfig.json'), 'migrations-path': ...

Issue encountered while retrieving the response, in case the node.js server sends the response with a delay

My aim is to upload an image and have the nodeJS server send the path of that image folder back as a response. Unfortunately, when I try sending the response after completing a task, nothing seems to be happening on the angular-side. Below is my componen ...

How can you determine the number of times a particular digit appears around a specific position in a TypeScript array

(Utilizing Typescript for assistance) I am looking to determine the number of occurrences of the digit 2 surrounding a specific position within an array. The function takes in the position coordinates as parameters - param 1 for row and param 2 for column. ...

An error occurred while trying to load the configuration "next/core-web-vitals" for extension

If you're embarking on a new project using NextJs and TypeScript, chances are you may encounter the following error: Failed to load config "next/core-web-vitals" to extend from. Wondering how to resolve this issue? ...

How to access nested JSON elements in Javascript without relying on the eval function

Below is a JSON that I am trying to access. { "orders": { "errorData": { "errors": { "error": [ { "code": "ERROR_01", "description": "API service is down" } ] } }, "status": " ...

Understanding the Meaning of npm Error Messages and Troubleshooting Solutions

When attempting to update my computer with the latest packages, I encountered errors while running: npm update -g The errors displayed were as follows: [XX001122][DESKTOP-N4A1752] $ npm update -g npm WARN deprecated <a href="/cdn-cgi/l/email-protecti ...

Tips for incorporating auth0 into a vue application with typescript

Being a beginner in TypeScript, I've successfully integrated Auth0 with JavaScript thanks to their provided sample code. However, I'm struggling to find any sample applications for using Vue with TypeScript. Any recommendations or resources would ...

Tips for incorporating the ternary operator in JSX of a React component while utilizing TypeScript?

I am looking to implement a conditional rendering logic in React and TypeScript, where I need to return null if a specific condition is met, otherwise render a component using a ternary operator. Here is the code snippet I currently have: {condition1 && ...

The absence of transpiled Typescript code "*.js" in imports

Here is an example of the code I am working with: User.ts ... import { UserFavoriteRoom } from "./UserFavoriteRoom.js"; import { Room } from "./Room.js"; import { Reservation } from "./Reservation.js"; import { Message } from ...

Achieving efficient filtering with multiple search parameters using a for loop in Vue Bootstrap

Something strange is happening with my table. I have set up filters in each column, but as soon as I enter any value, all the items disappear without any error message showing up in the console. Let me share the code snippet: <template> <div> ...

Issue: The CSS loader did not provide a valid string output in Angular version 12.1.1

I am encountering 2 error messages when trying to compile my new project: Error: Module not found: Error: Can't resolve 'C:/Users/Avishek/Documents/practice/frontend/src/app/pages/admin/authentication/authentication.component.css' in &apos ...

Enabling HTML and Markdown in the footer of VuePress

I am currently attempting to incorporate HTML/markdown into the footer variable within VuePress' default theme. My goal is to include a URL in the footer that directs visitors to my website. Unfortunately, I have been unable to find a straightforward ...

Getting the Most Out of .find() in Angular 4

Despite reading various similar questions, I'm still struggling to make the .find() function work in my application. I have a service with the following API: export class VehicleService { private defUrl = 'API'; constructor(private ht ...

When merging multiple prop definitions using Object.assign in defineProps, Vue props can be made optional

I have defined a const called MODAL_OPTION_PROP to set common props for a modal: export const MODAL_OPTION_PROP = { modalOption: { type: Object as PropType<ModalOptionParams>, default: DEFAULT_MODAL_OPTION, }, }; I am trying to use it in ...

Issue with TypeScript retrieving value from an array

Within my component.ts class, I have defined an interface called Country: export interface Country{ id: String; name: String; checked: false; } const country: Country[] = [ { id: 'India', name: 'India', checked: false}, { ...

Angular 2 code test coverage

Looking to calculate the code coverage of my Angular 2 code. Wondering if there are any plugins available for VS Code or WebStorm that can assist with this. My unit testing is done using Jasmine and Karma. ...

What is the best way to update an array in TypeScript when the elements are of different types and the secondary array has a different type as

const usersData = [ { "id": 0, "name": "ABC" }, { "id": 1, "name": "XYZ" } ]; let dataList = []; // How can I transfer the data from the user array to the dataList array? // If I use the map function, do I need to initialize empty values for oth ...

Integrate service once the constructor has completed execution

I created a service to connect with the Spotify API. When initializing this service in the constructor, it needs to retrieve the access token by subscribing to an Observable. However, there's an issue: The service is injected into my main component ...

Resolving the Error: "Type 'Customer | undefined' is not compatible with type 'Customer'" in Angular

I encountered an issue with the following code: ... export class ListCustomersComponent implements OnInit { customers: Array<Customer> = []; showCustomer?: Customer; isSelected: boolean = false; deletedCustomer?: Customer; returnedMessa ...