Transfer the unique field name to a universal assistant

Consider the code snippet provided in this playground:

class A {
  private z = 0
}

type K = "z"
type ValidKeys = A[K] extends any ? K : never

The type ValidKeys compiles correctly and matches K only when K represents a subset of keys from A. It will not compile if additional keys are added to K like:

type K = "z" | "not-a-key"

This behavior is desired, but I am looking to make ValidKeys generic based on A and K:

type ValidKeys<A, K> = ...

How can I achieve this type definition?


Why is it necessary?

When working with mobx, the documentation states:

  1. Private fields cannot be annotated by default in TypeScript. To overcome this, relevant private fields need to be explicitly passed as generic arguments, like so:
    makeObservable<MyStore, "privateField" | "privateField2">(this, { privateField: observable, privateField2: observable })

Hence, I require passing a type containing specific private keys to a generic function. Using literals may lead to runtime issues if properties are renamed.

Instead of:

constructor() {
  makeObservable<Store, "x" | "y">(this, { x: observable, y: false })
}

I aim to write:

constructor() {
  makeObservable<Store, ValidKeys<Store, "x" | "y">>(this, { x: observable, y: false })
}

To catch key renaming errors at compile-time.

The current workaround involves manually adding a snippet within the constructor:

constructor() {
  type ExtraKeys = "x" | "y"
  type _CompilesIfOk_ExtraKeys = Store[ExtraKeys]
  makeObservable<Store, ExtraKeys>(this, { x: observable, y: false })
}

I am seeking a simpler solution for this and intend to move it into a helper function.

Answer №1

Currently, it seems unlikely that this can be achieved because private members are not enumerable in keyof. This limitation is why MobX requires you to provide the keys manually, as there is no automatic solution available.

Although it may compromise type safety, there are currently no widespread solutions to address this issue.

The topic is also being discussed on Github: https://github.com/microsoft/TypeScript/issues/22677

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

The typescript error "Cannot read properties of undefined" is encountered while trying to access the 'map' function

I was attempting to follow a guide on creating an app using typescript and react, but I'm encountering an error that says "Cannot read properties of undefined (reading 'map')". I'm not sure why this is happening, can someone please offe ...

Seeking clarification on how the Typescript/Javascript and MobX code operates

The code provided below was utilized in order to generate an array consisting of object groups grouped by date. While I grasped the overall purpose of the code, I struggled with understanding its functionality. This particular code snippet is sourced from ...

Experiencing a 404 ERROR while attempting to submit an API POST request for a Hubspot form within a Next.js application

Currently, I am in the process of developing a Hubspot email submission form using nextjs and typescript. However, I am encountering a couple of errors that I need help with. The first error pertains to my 'response' constant, which is declared b ...

Leave the Private NPM Repository

Alright, maybe this is a silly question but I can't seem to locate the information anywhere and I'm sure I'm not the only one who has wondered... I've been relying on my company's internal NPM Repo for quite some time now that I&a ...

Guide on integrating angular-schema-form into an Ionic 2.0 project using typescript

Recently, I embarked on creating an app with Ionic from scratch and decided to integrate the framework. While I faced no issues executing the example on a webpage, I encountered difficulties when attempting to do so with Ionic. To kickstart the project, ...

There was an issue while attempting to differentiate '[object Object]'. Ionic only allows arrays and iterables for this operation

I am looking for a way to extract all the "friend" objects from a JSON response and store them in an array so that I can iterate through them on an HTML webpage. ...

The production build encountered an error after upgrading Angular due to a problem with document.documentElement.setAttribute not being recognized

Recently, I updated my application to Angular 16 and the upgrade was successful. The application is running smoothly without any issues. However, when I attempted to run the command for a production build, ng build --configuration=production I encountere ...

ESLint encountered an issue: Reserved keyword 'interface' triggered a parsing error

Whenever I utilize the most recent version of eslint to initiate a project, a specific error pops up: import { ref } from 'vue' defineProps<{msg: string}>() const count = ref(0) Error message: Unexpected token )eslint Adjusting the code ...

Are npm @types packages causing issues in Visual Studio?

Nowadays, TypeScript's type packages are typically found in node packages with the format @types/packagename. Strangely, Visual Studio, despite its support for npm packages, appears to be unable to locate them: https://i.sstatic.net/7tOK1.png The s ...

Acquiring JSON-formatted data through the oracledb npm package in conjunction with Node.js

I am currently working with oracledb npm to request data in JSON format and here is the select block example I am using: const block = 'BEGIN ' + ':response := PK.getData(:param);' + 'END;'; The block is ...

Angular type error: Attempting to assign a value of type 'string' to a variable declared as type 'string[]' is not allowed

As a newcomer to Angular, I am currently working on building an electron app with Angular 6. My objective is: 1. Implementing SupportInformationClass with specific definitions 2. Initializing the component to populate the definitions from electron-settin ...

Describing the implementation of UNO out parameters within definitions

The UNO API offers support for inout and out parameters. In this scenario, a variable is passed into a function, the function modifies the variable, and the updated value of the variable can be accessed outside the function. Javascript lacks native suppor ...

Using Typescript and JSX to render a component that has been passed as an argument

I am seeking to create a function that will render a React component passed as an argument. I aim to accommodate both Component and StatelessComponent types with the following approach: function renderComponent(component: React.ComponentClass<any> | ...

Tips on incorporating jstree into an Angular 2 application with TypeScript and @types/jstree

Hello, I am new to ng2 and have a question that may seem obvious to some. I recently installed the jstree library using npm in my angular-cli application by running the command npm i jstree --save. Following this, I also installed the types for jstree wi ...

Make sure to send individual requests in Angular instead of sending them all at once

I am looking to adjust this function so that it sends these two file ids in separate requests: return this.upload(myForm).pipe( take(1), switchMap(res => { body.user.profilePic = res.data.profilePic; body.user.coverPic = res.data.coverPic; ...

Angular 4 with Typescript allows for the quick and easy deletion of multiple selected rows

I am currently working on an application where I need to create a function that will delete the selected checkboxes from an array. I have managed to log the number of checkboxes that are selected, but I am struggling to retrieve the index numbers of these ...

Module not found in Typescript

Filter.ts, mustache.js and redux.3.5.2.js are all located in the same directory (/Scripts). The code snippet within Filter.ts is as follows: ///<reference path="./typings/mustache.d.ts" /> import Mustache = require("mustache"); import Redux = requir ...

Limit the range of potential inputs for the function parameter

class Coordinate { constructor(readonly x: number, readonly y: number) {} } const Up = new Coordinate(0, -1); const Right = new Coordinate(1, 0); const Down = new Coordinate(0, 1); const Left = new Coordinate(-1, 0); // How can we restrict the directio ...

Is it possible to dynamically insert additional fields when a button is clicked?

My FormGroup is shown below: this.productGroup = this.fb.group({ name: ['', Validators.compose([Validators.required, Validators.maxLength(80)])], desc: ['', Validators.maxLength(3000)], category: ['', Validators.require ...

Alert: Prop type validation error: The `component` prop provided to `ForwardRef(Link)` is invalid

We are facing an issue with our NextJS app where it works fine in production, and locally it renders correctly. However, we are encountering some unsightly warnings that we are trying to suppress. client.js:1 Warning: Failed prop type: Invalid prop `compon ...