Validate the data type based on the property

I have a CARD type that can be either a TEXT_CARD or an IMAGE_CARD:

declare type TEXT_CARD = {
  type: "paragraph" | "h1" | "h2";
  text: string;
};

declare type IMAGE_CARD = {
  type: "img";
  src: string;
  orientation: "portrait" | "landscape";
};

declare type CARD = TEXT_CARD | IMAGE_CARD;

When displaying a card, I need to switch between these two to render separate components.

<!-- index.svelte -->
<script lang="ts">
  import TextCard from "./TextCard.svelte";
  import ImageCard from "./ImageCard.svelte";
  export let card: CARD;
</script>

{#if ["paragraph", "h1", "h2"].includes(card.type)}
  <TextCard {card} />
{:else}
  <ImageCard {card} />
{/if}



<!-- TextCard.svelte -->
<script lang="ts">
  export let card: TEXT_CARD;
</script>

<h1>{card.text}</h1>



<!-- TextCard.svelte -->
<script lang="ts">
  export let card: IMAGE_CARD;
</script>

<h1>{card.src}</h1>


However, TypeScript is now throwing an error in index.svelte, saying that CARD is not assignable to TEXT_CARD.

Type 'CARD' is not assignable to type 'TEXT_CARD'.

How and where should I assert that I am certain I am dealing with a TEXT_CARD / IMAGE_CARD? Or should I restructure my types from the beginning?

Answer №1

One approach to consider is defining

["paragraph", "h1", "h2"]
in a constant variable. By doing this, you can explicitly specify the correct type to TypeScript as shown below:

const CUSTOM_TYPES: CARD['type'][] = ["paragraph", "h1", "h2"]

With this setup, TypeScript will no longer generate errors when utilizing it in the following manner:

{#if CUSTOM_TYPES.includes(card.type)}
  ...
{/if}

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

Angular: Disabling a button based on an empty datepicker selection

Can anyone help me figure out how to disable a button when the datepicker value is empty? I've tried using ngIf to check if the datepicker is empty and then disable the button, but it's not working. My goal is to make the button unclickable if th ...

Exploring dependency injection in Angular 1 using a blend of JavaScript and TypeScript

I'm currently working on integrating TypeScript into an existing Angular 1.5 application. Despite successfully using Angular services and third-party services, I am facing difficulties in injecting custom services that are written in vanilla JavaScrip ...

Choosing several buttons in typescript is a skill that every programmer must possess

I need help with selecting multiple buttons in TypeScript. The code I tried doesn't seem to be working, so how can I achieve this? var input = document.getElementById('input'); var result = document.getElementById('result'); v ...

Experiencing browser crashes following the incorporation of asynchronous functions into a JavaScript file. Seeking solutions to resolve this

In my recent project, I developed a basic online store application using vanilla javascript and ES6 classes. The shop items are stored in a JSON file which I used to populate the user interface. To implement functions like "addToCart", "quantityChange", a ...

When I select a checkbox in Angular 2, the checkall function does not continue to mark the selected checkbox

How can I check if a checkbox is already marked when the selectAll method is applied, and then continue marking it instead of toggling it? selectAll() { for (let i = 0; i < this.suppliersCheckbox.length; i++) { if (this.suppliersCheckbox[i].type == " ...

Transform Loopback 4 filter into a SQL WHERE condition

When using Loopback 4, the filter object that is received by functions like Get and Count appears as shown below: { where: { property: { op: value; } } } I am interested in converting this structure into an SQL WHERE clause to use it in ...

The blank screen mystery: ionic and Google maps integration not playing nice

I've been struggling to integrate Google Maps into my web application. Unfortunately, all I see is a blank screen with no errors. Here's the current code snippet that I have. It seems like there might be an issue with the mapElement variable, but ...

Sending a style prop to a React component

My typescript Next.js app seems to be misbehaving, or perhaps I'm just not understanding something properly. I have a component called <CluckHUD props="styles.Moon" /> that is meant to pass the theme as a CSS classname in order to c ...

Encountering a compilation error while trying to utilize a union type in a function parameter within an

As stated on https://www.typescriptlang.org/docs/handbook/declaration-files/do-s-and-don-ts.html, it is recommended to utilize multiple types for a parameter in a function (refer to the union part) /* OK */ interface Moment { utcOffset(): number; ...

In Typescript, it is not possible to assign the type 'any' to a string, but I am attempting to assign a value that is

I'm new to TypeScript and currently learning about how types function in this language. Additionally, I'm utilizing MaterialUI for this particular project. The issue I'm encountering involves attempting to assign an any value to a variable ...

Angular button for opening or closing the menu that redirects the page to a localhost URL

I have implemented a template from the link below into my project. So far, everything has been working fine, but recently I noticed that the menu open/close button is malfunctioning. Whenever I click on the close button while on any page (for example, http ...

Nativescript encountered an error due to an undefined variable called FIRAuth

I'm currently working on a project using Nativescript. While everything runs smoothly with Firebase on the local emulator, I encounter errors when testing the application on my iPhone. The specific error message is: CONSOLE LOG file:///app/vendor.js ...

Creating a dynamic columns property for Mat-Grid-List

Is it possible to create a Mat-Grid-List where the number of columns can be dynamically changed based on the width of the container? Here is an example: <mat-grid-list [cols]="getAttachmentColumns()" rowHeight="100px" style="width: 100%;"> <mat ...

Using injected services within static methods may seem tricky at first, but once you

I am exploring the integration of angularjs and typescript in my project. Currently, I am working on creating an Orm factory using typescript but have encountered some challenges. The structure of my factory class is as follows: class OrmModel implements ...

Is it possible to have an optional final element in an array?

Is there a more graceful way to declare a Typescript array type where the last element is optional? const example = (arr: [string, string, any | undefined]) => console.log(arr) example(['foo', 'bar']) When I call the example(...) f ...

Discovering the country associated with a country code using ngx-intl-tel-input

In my application, I am trying to implement a phone number field using this StackBlitz link. However, I have observed that it is not possible to search for a country by typing the country code (e.g., +231) in the country search dropdown. When I type a coun ...

Converting TypeScript to ES5 in Angular 2: A Comprehensive Guide

I am currently diving into Angular 2 and delving into Typescript to create simple applications within the Angular 2 framework. What I have discovered is that with Typescript, we can utilize classes, interfaces, modules, and more to enhance our application ...

Create an interactive Angular form that dynamically generates groups of form elements based on data pulled from

I am currently developing an Angular application and working on creating a dynamic form using Angular. In this project, I am attempting to divide the form into two sections: Person Name and Personal Details. While I have successfully grouped fields for P ...

The trouble with React Navigation encountered with TypeScript: This Entity Cannot Be Invoked

Currently, I'm facing a typescript issue after upgrading to React Navigation 5. The specific error message reads: There is an issue with calling this expression. The union type '{ <RouteName extends "Stack1Screen1" | "Home&quo ...

Initiate asynchronous ngOnInit

Can ngOnInit() actually return a promise? I've noticed a common practice where developers use this approach and it appears to be functional. However, there is a risk with unobserved promises as they can be resolved or rejected at unexpected times, s ...