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

What causes Node.js to crash with the Headers already sent Error while managing errors in Express?

My current project involves using Express to set up an API endpoint for user registration. However, I've encountered a problem where sending a request that triggers an error to this API endpoint causes my node.js server to crash. The specific message ...

Sign up for a feature that provides an observable exclusively within an if statement

There is an if clause in my code that checks for the presence of the cordova object in the window global object. If cordova is present, it will make a http request and return the default angular 2 http observable. If the application is in a web context wh ...

Using TypeScript, let's take a closer look at an example of Angular

I am trying to replicate the chips example found at this link (https://material.angularjs.org/latest/#/demo/material.components.chips) using TypeScript. I have just started learning TypeScript this week and I am having some difficulties translating this co ...

The process of automatically formatting Typescript has transformed into an unfortunate auto-discarding action

Typescript autoformatting has become a concerning issue. Whenever I input quoted strings (" or `), the code surrounding it seems to temporarily glitch, with other strings appearing as code. This problem has recently escalated, particularly with strings li ...

Challenges of implementing dark mode with a checkbox and local storage

I'm experiencing an issue with local storage. When I enable the dark mode, everything functions properly and the local storage 'dark' is set to true. However, upon refreshing the page, the local storage remains true but the toggle switches b ...

Next.js does not recognize Typescript Context

I encountered an unexpected custom error while trying to implement custom error notifications in my form. The custom context I set up for this functionality does not seem to be working as intended, resulting in a thrown error for its non-existence. My deve ...

Which superclass does ReadonlyArray extend from?

Looking at this TypeScript code snippet: const arr: ReadonlyArray<string> = [ "123", "234" ]; arr.push("345"); An error is thrown by the TS compiler: Property 'push' does not exist on type 'ReadonlyArray<string>&apo ...

The TypeScript compiler is unable to locate the name 'window'

Within my Meteor/React project, I encounter the following line of code: let gameId = window.prompt("Please input the ID of the game you would like to load."); The TypeScript compiler presents an error during transpiling: Cannot find name 'window&apo ...

The call to react.cloneElement does not match any overloads

I'm encountering a typescript error in my React code when using React.cloneElement with the first parameter "children", and I am unsure of how to resolve it. As a newcomer to typescript, I believe that the type definitions in index.d.ts for cloneElem ...

Why is my custom 404 page failing to load after building my Next.js application?

I recently set up a custom 404 page for my Next.js app and wanted to test it locally before deploying to the server. To do this, I used the "serve" package to host the project on my local machine. However, when I tried navigating to a non-existent page, th ...

Although there may be some issues with tslint, the functionality is operating smoothly

I am in the process of learning tslint and typescript. Currently, I am facing an issue that I need help with. Could you provide guidance on how to resolve it? Despite conducting some research, I have been unable to find a solution. The relevant code snippe ...

Next.js is failing to infer types from getServerSideProps to NextPage

It seems like the data type specified in getServerSideProps is not being correctly passed to the page. Here is the defined model: export type TypeUser = { _id?: Types.ObjectId; name: string; email: string; image: string; emailVerified: null; p ...

One typical approach in React/JavaScript for monitoring the runtime of every function within a program

Experimenting with different techniques such as performance.now() or new Date().getTime() has been done in order to monitor the processing time of every function/method. However, specifying these methods within each function for time calculation purposes h ...

What could be the reason for encountering TypeScript within the Vue.js source code?

While exploring the vue.js source code, I stumbled upon some unfamiliar syntax that turned out to be TypeScript after further investigation. What baffled me was finding this TypeScript syntax within a ".js" file, when my understanding is that TypeScript ...

WebStorm displays all imported items as unused in a TypeScript backend project

https://i.stack.imgur.com/J0yZw.png It appears that the image does not display correctly for files with a .ts extension. Additionally, in .tsx files, it still does not work. In other projects using WebStorm, everything works fine, but those projects are o ...

Encountering an ERROR during the compilation of ./src/polyfills.ts while running ng test - Angular 6. The module build

I encountered a problem in an angular project I am working on where the karma.config was missing. To resolve this, I manually added it and attempted to run the test using the command ng test. However, during the execution, an error message appeared: [./src ...

Angular's error notification system seems to be lacking in providing accurate

I'm experiencing an issue with my angular app where errors are not displayed properly. Instead of showing errors in the component and line number, they always appear in main.js. This is different from how errors are displayed in my other angular appli ...

React/TypeScript - react-grid-layout: The onDrag event is fired upon clicking the <div> element

I am currently working on creating a grid with clickable and draggable items using the react-layout-grid component. However, I am facing an issue where the drag is instantly activated when I click on the item without actually moving the cursor. Is there a ...

Utilizing Conditional Aurelia Validation Based on Element's Display Status

Currently, I am in the process of setting up a license subscription form using Aurelia and the Aurelia Validation plugin. Within this form, there is a fieldset dedicated to personal information which contains mostly required fields that are validated by Au ...

Developing a custom package containing personally crafted type definitions and importing them into the project

I'm in need of creating a private npm package specifically for custom type definitions (typedefs) that are hand-written d.ts files not generated by TypeScript. Since these are proprietary, they cannot be added to DefinitelyTyped. The folder structure ...