Can you identify a specific portion within an array?

Apologies for the poorly titled post; summarizing my query into one sentence was challenging.

I'm including the current code I have, as I believe it should be easy to understand.

// Constants that define columns
const columns = ["a", "b", "c"] as const

// Defining editable columns using a subset of the columns
type EditableColumns = readonly (typeof columns[number])[]

// Specify which columns are editable
const editableColumns: EditableColumns = ["a", "b"] as const

type Props<T> = { data: readonly T[], editableColumns: EditableColumns }

// The goal is to add extra info only to editable columns and exclude others
type Foo<U, T extends Props<U> = Props<U>> = {
  [key in typeof columns[number]]: key extends T["editableColumns"][number]
    ? {
        readonly column: key
        readonly row: U
        readonly extraInfo: "HELLO"
      }
  : {
      readonly column: key
      readonly row: U
    }
}

let foo = {} as Foo<string>

// Currently, all columns receive the extra info,
// even though 'foo.c' shouldn't. Hover over 'foo.c' to verify.
foo.a
foo.b
foo.c

// How can I ensure only 'a' and 'b' get the extra info while excluding 'c'?

playground link

Answer №1

Your code snippet defining `editableColumns` is not utilized in the `Foo` type definition. If you modify it as shown below, the column `foo.c` will be restricted according to your specified criteria:

const columns = ["a", "b", "c"] as const;

type EditableColumns = readonly (typeof columns[number])[];

const editableColumns = ["a", "b"] as const;

type Props<T> = { data: readonly T[], editableColumns: EditableColumns };

type Foo<U> = {
  [key in typeof columns[number]]: key extends (typeof editableColumns)[number]
    ? {
        readonly column: key
        readonly row: U
        readonly extraInfo: "HELLO"
      }
  : {
      readonly column: key
      readonly row: U
    }
};

let foo = {} as Foo<string>;
foo.a;
foo.b;
foo.c;

It's a bit unclear what your end goal is with this setup.

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

Navigating the NextJS App Directory: Tips for Sending Middleware Data to a page.tsx File

These are the repositories linked to this question. Client - https://github.com/Phillip-England/plank-steady Server - https://github.com/Phillip-England/squid-tank Firstly, thank you for taking the time. Your help is much appreciated. Here's what I ...

Show a condensed version of a lengthy string in a div using React TS

I've been tackling a React component that takes in a lengthy string and a number as props. The goal of the component is to show a truncated version of the string based on the specified number, while also featuring "show more" and "show less" buttons. ...

Exploring Tailwind's flexibility with custom color schemes

I'm attempting to generate unique hex colors for my React/TypeScript application with Tailwind. Why isn't the background color updating based on the color variable value? Check out my code snippet below: import React, { useState } from &apo ...

Is it possible to verify .0 with regular expressions?

In my project, I have a field that requires whole numbers only. To validate this, I used a regex validation /^\d{1,3}$/ which successfully validates whole number entry and rejects decimal points starting from .1. However, I encountered an issue where ...

Having trouble with the .d.ts module for images?

I'm relatively new to Typescript and the only thing that's giving me trouble is the tsconfig.json. My issue revolves around importing images (in Reactjs) and them not being found: client/app/Reports/View.tsx:11:30 - error TS2307: Cannot find mod ...

Selecting the optimal data structure: weighing the benefits of using boolean check versus array .include (balancing performance and redundancy

My objects can have one or more properties assigned, with a total of 5 different properties in my case. To illustrate this, let's use a simple movie example where each movie can be assigned from 5 different genres. I have come up with two methods to ...

Converting a string[] to an EventEmitter string[] in Angular 4 with TypeScript: Step-by-step guide

Programming Language: Typescript – written as .ts files Development Framework: Angular 4 I'm currently working on an application that is supposed to add chips (similar to tags in Angular 1) whenever a user types something into the input box and hi ...

Typescript classes implementing data hydration and dehydration techniques

Exploring ways to share TypeScript classes or interfaces between a React + TS frontend and node + TS backend. Converting class instances into JSON poses a challenge as TS types are removed during compile time. Considering options for defining objects in a ...

Looking to create universal React component wrappers?

I am working with a set of functional components that share a common set of properties, for example: const A = ({ x, y, z }) = {...} const B = ({ x, y, z }) = {...} For these components, I have predefined configurations: const styles { A: { ty ...

What is the best method to add data to a child array located within a nested array?

Struggling to create an array that will display data in the following format: Healthcare -- Insights driven by data for improved healthcare -- Urban Analytics Transport -- Urban Analytics Cities -- Urban Analytics I have attempted ...

Issue in TypeScript where object properties may still be considered undefined even after verifying using Object.values() for undefined values

I'm encountering an issue with TypeScript regarding my interface MentionItem. Both the id and value properties are supposed to be strings, but TypeScript is flagging them as possibly string | undefined. Interestingly, manually checking that id and va ...

Guide on setting a default value for a variable within a Typescript class

In the process of developing a component to manage information about fields for form use, I am in need of storing different data objects in order to establish generic procedures for handling the data. export class DataField<T> { /** * Field ...

I'd like to know how to retrieve a total count of all the documents within a Firebase collection using Angular

My code currently fetches documents from a collection, but it's only bringing back 15 at a time (from what I can gather). This is causing an issue as I need to accurately determine the total number of documents in the collection for a program I'm ...

The type does not meet the requirements set by the class it is inheriting from

Currently, I am in the process of working on a WebSocket Secure (WSS) server utilizing the Node ws library which can be found here. More specifically, I am following the approach outlined in this particular question, although its relevance is yet to be det ...

I've been working on setting up a navbar in React/typescript that links to various routes, but I've hit a snag - every time I try to create a link

import React from 'react' import { Link } from 'react-router-dom' export default function NavBar() { return ( <div className='NavContainer'> <link to='/home'>Home</link> <l ...

Typescript Error: Trying to access a property that is undefined

I am a beginner in typescript and believe that the issue I am facing is related to typescript. Currently, I am working on an Ionic app where I have a function setwall() being called from home.html. The setwall() function is defined in home.ts. However, whe ...

Using rxjs takeUntil will prevent the execution of finalize

I am implementing a countdown functionality with the following code: userClick=new Subject() resetCountdown(){this.userClick.next()} setCountDown() { let counter = 5; let tick = 1000; this.countDown = timer(0, tick) .pipe( take(cou ...

Errors caused by Typescript transpilation only manifest on the production server

During the process of updating my node version and dependencies on both machines, I came across an issue where building my app in production on one machine resulted in an error, while building it on my main machine did not. I found that the errors disappe ...

Issue with Angular 9 application: Unable to properly render form fields within a Material Design Dialog

I'm currently developing a "Tasks" application using Angular 9 and PHP. I've encountered an error that says Cannot find control with name: <control name> when attempting to pre-fill the update form with data. Here is the form template: &l ...

Exploring Typescript: Enhancing the functionality of `export = Joi.Root`

I've noticed that the types for @hapi/joi appear to be outdated - some configuration parameters mentioned in the official documentation are missing from the types. To address this, I am attempting to enhance the existing types. node_modules/@types/ha ...