Uncertain entities in Typescript

I used to use Flow for typing. How can I type an imprecise object?

Here's the array I'm working with:

const arr = [
        {label: 'Set', value: setNumber, id: 'setNumber', set: setSetNumber, type: 'text'},
        {label: 'Name', value: name, id: 'name', set: setName, type: 'text'},
        {label: 'Source', value: source, id: 'source', set: setSource, type: 'text'}
    ]

The type inference works well except that I want 'type' to be:

type InputType = 'text' | 'number'

How can I define this one property without affecting the inference of the other properties?

Answer №1

For improved type safety, consider adding as const to the relevant strings like so:

[
        {label: 'Set', value: setNumber, id: 'setNumber', set: setSetNumber, type: 'text' as const},
        {label: 'Name', value: name, id: 'name', set: setName, type: 'text' as const},
        {label: 'Source', value: source, id: 'source', set: setSource, type: 'text' as const}
    ]

This informs TypeScript that these are literals and not just plain strings.

Answer №2

One approach is to create a new variable where the type is inferred from the existing one by explicitly casting the 'type' property of each item:

var itemList = [
    { label: 'Quantity', value: quantity, id: 'qty', set: setQuantity, type: 'number' },
    { label: 'Name', value: name, id: 'name', set: setName, type: 'text' },
    { label: 'Category', value: category, id: 'cat', set: setCategory, type: 'text' }
];

var filteredList = itemList as Array<typeof itemList[number] & { type: 'text' | 'number' }>;

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

Deduct x days from a Date String in a React Component

How can I subtract a specified number of days from a date that is in string format, like "2021-07-19"? I attempted to convert the string into a date, subtract the days, and then convert it back to a string, but this method did not produce the desired resu ...

Executing a function by clicking on a DIV with the value of a textbox, instead of clicking directly on the textbox

Here is a function I have: $("#border-radius").click(function(){ var value = $("#border-radius").attr("value"); $("div.editable").click(function (e) { e.stopPropagation(); showUser(value, '2', this.id) $(this).css( ...

What is the best way to automatically add a date and timestamp to every new entry?

I am currently working on a project that utilizes AngularJS and Ionic frameworks. The main feature of the project will involve users inputting data to create a list, and allowing any user to comment on each item in the list. One challenge I have encounter ...

Develop a set of matching key/value pairs using TypeScript

Looking to develop a custom data type where InputKeys will serve as the keys, and the values will be key/value pairs. The keys should correspond to InputFieldKey, with the value being a string. My current progress includes {[key: string]: string}, but I n ...

Activating Button within Featherlight Modal

This is a follow up question from Featherlight hide div on Close After successfully resolving the issue with opening the lightbox, I have encountered another problem. I have added a submit button that should trigger an on('submit', function) whe ...

Transform JSX into JSON or a string, then reverse the process

I am looking to store the state of a React Component in a database. Json.stringify(myComponent); However, when I attempt to reuse the component using JSON.parse, I encounter Error: Objects are not valid as a React child (found: object with keys {type, k ...

Leveraging the power of JavaScript and jQuery to identify comparable SELECT choices

My current approach involves utilizing the .filter() method to match the value of an INPUT field (prjName) with an option in a SELECT field (prjList). However, this method only works when there is an exact match for the option text: $("select[title=' ...

Creating a Vue component that leverages the computed property from a mixin

My situation involves a straightforward component that utilizes a mixin shared across various components that have similar functionalities. However, upon running it, an issue arises: The error message "Property or method 'activeClass' is not ...

What is the best way to turn each function within the module pattern into a promise?

Utilizing Angular 1.5, I have developed a factory function that returns a literal object structured as follows: return { item: null, get: function() { return item; }, create: function() { if (this.get()){ this.remove(); ...

Shared Vue configuration settings carrying over to Jest spec files

For my unit testing of components using VueJS and Jest, I'm incorporating the Bootstrap Vue library for styling. To address console warnings regarding unknown plugins, I've set up a configuration file: import { createLocalVue } from '@vue/t ...

Using an external script to modify or call a Vue.js method

My Vue app is constructed using Webpack and includes a few basic computed properties, such as calculating the sum amount from input values. However, I now require the capability to replace the summation function with one stored in a separate file that is n ...

What is the method for verifying PHP information using jQuery AJAX?

On my PHP page, I have an else statement that filters data from a SQL database based on user input. Below is some pseudo code: NextPage.php //Include database configuration file include('../dbConfig.php'); if(isset($_POST['pageno']) ...

"Ensuring Contact Information is Unique: A Guide to Checking for Existing Email or Phone Numbers in

I'm encountering an issue with validating email and phone numbers in my MongoDB database. Currently, my code only checks for the presence of the email but does not respond to the phone number. const express = require("express"); const router ...

Tips for keeping the app on the same route or page even after a refresh

I'm currently diving into the world of React and am in the process of constructing a CRUD application. I've successfully created multiple pages that utilize react-router-dom for navigation with authentication. The pages are accessible only to log ...

CSS swapping versus CSS altering

Looking to make changes to the CSS of a page, there are two methods that come to mind: Option 1: Utilize the Jquery .css function to modify every tag in the HTML. For instance: $("body").css("background : red") Alternatively, you can disable the current ...

Oops! It seems like there was an issue trying to access properties that are undefined while reading 'pipe' in Angular12

I encountered an issue when trying to send an AJAX request, displaying the following error message: ERROR TypeError: Cannot read properties of undefined (reading 'pipe') This error occurred in the ajax-loader.interceptor.ts class export class A ...

The button's URL will vary depending on the condition

As a newcomer to coding, I am seeking guidance on creating a button with dynamic URLs based on user input. For instance, let's say the button is labeled "Book Now" and offers two package options: Standard and Premium. I envision that if a user selec ...

Utilizing Jquery for Enhanced HTML5 Validation

I need to ensure compatibility with browsers that do not support HTML5 validation. My goal is to display the basic error message from the browser using HTML5, while also adding a CSS class of "error" to each input, label, and parent div for fields with err ...

Creating the document.ready function in Angular2 with JQuery

I am seeking assistance to modify the JQuery function so that it can run without the requirement of a button click. Currently, the function only executes when a button is clicked. Code declare var jQuery: any; @Component({ selector: 'home-component ...

The compatibility issue between styled-components and create-react-library is causing some functionality to

Upon attempting to import styled-components into a create-react-library module, I encountered an error message: Error: 'typeOf' is not exported by node_modules\react-is\index.js, imported by node_modules\styled-components\dist ...