What is the methodology for obtaining the setter property type in TypeScript?

Describe a scenario where an object contains both getter and setter methods with different types. How can we determine the type of the setter function?

Consider defining an object with getter and setter functions like the example below:

type Foo = {
    get bar(): number;
    set bar(value: number | string);
}

In this setup, it's straightforward to retrieve the type of the getter method. However, determining the type of the setter poses a challenge.

type Bar = Foo["bar"]; // This will return 'number'

Is there a way to ascertain the type of the setter, such as 'number' or 'string' in the given example?

I've made an attempt at a solution without success.

type SetterType<T, U extends string> = T extends { set [key in U]: infer P } ? P : never;
type Bar = SetterType<Foo, "bar">;

Implementation Applications:

Let's suppose we have an API structured as follows:

const foo = addFoo(); // The function addFoo returns type Foo.
foo.bar = 123;
foo.bar = "123"; // Setting the property works correctly with varying types.
foo.baz = true;
// additional properties...

We aim to wrap this functionality by representing these attributes using a literal object.

This wrapping mechanism will leverage Object.assign internally.

function myAddFoo(properties: Partial<Foo>): Foo {
    const foo = addFoo();
    Object.assign(foo, properties);
    return foo;
}

const foo = myAddFoo({
    bar: "123", // Error - 'bar' must be of type number or undefined.
    baz: true,
    // other properties...
});

The 'bar' property within the literal object cannot accept values conforming to the setter type 'number | string'. To resolve this, the function arguments should accommodate the setter type.

type FooSetters = /* Infer all setters type, e.g., `{ bar: number | string }` */;
function myAddFoo(properties: Partial<Omit<Foo, keyof FooSetters> & FooSetters>): Foo

Answer №1

When working with a basic Equal, it becomes clear that comparing types may not be as straightforward as expected. In such cases, one must either accept the limitation or explore alternative solutions to achieve the desired outcome.

export type Equal<A, B> =
  (<T>() => T extends A ? 1 : 2) extends
  (<T>() => T extends B ? 1 : 2) ? true : false

type example = Equal<{
  get value(): 1;
  set value(newValue: 1 | 2);
},{
  get value(): 1;
  set value(newValue: 1 | 2 | 3);
}>

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

Exporting a constant as a default in TypeScript

We are currently developing a TypeScript library that will be published to our private NPM environment. The goal is for this library to be usable in TS, ES6, or ES5 projects. Let's call the npm package foo. The main file of the library serves as an e ...

What is the correct location for storing .html, .css, and other files in a project involving Typescript, Angular 2, and ASP.Net Core 1.0?

When following a Typescript tutorial to create an ASP.Net Core application (with or without Angular 2), it is recommended to set up a folder called Scripts and use gulp tasks to selectively copy only the .js files to the wwwroot folder during the build pro ...

Preventing data loss in an Ionic array - encountering issues with using this.array.push

When attempting to use the storage get method to fill the array storedArr = [], I encounter the error message .push is not a function: storedArr = this.storage.get('stored') ? this.storage.get('stored').then((e) => {e}) : []; The c ...

Having difficulty implementing a versatile helper using Typescript in a React application

Setting up a generic for a Text Input helper has been quite challenging for me. I encountered an error when the Helper is used (specifically on the e passed to props.handleChange) <TextInput hiddenLabel={true} name={`${id}-number`} labelText=" ...

Struggle with Transmitting Information in Ionic 2

I have been working on an Ionic project that involves a JSON file with preloaded data. The initial page displays a list from which a user can select an item to view its content. However, I am encountering a "Response with status: 404 Not Found for URL" err ...

What is the correct way to set up a custom class instance with specific parameters at the top level?

Is it possible to utilize the defineString(), defineInt, ... functions within a top-level custom class constructor? defineString() returns a StringParam object which has a value() method. I am looking to use parameterized configuration to initialize an in ...

Leverage C# model classes within your Angular application

Just wanted to express my gratitude in advance import { Component, Inject } from '@angular/core'; import { HttpClient } from '@angular/common/http'; @Component({ selector: 'app-fetch-data', templateUrl: './fetch-data. ...

What is the best way to incorporate an automatic scroll to the following section on a single page website

My goal is to implement a feature that enables automatic scrolling between sections as the user scrolls up or down. The smooth transition should occur when the user reaches halfway through each section, seamlessly moving to the next screen on the same page ...

Unable to retrieve files from public folder on express server using a React application

The Issue When trying to render images saved on the backend using Express, I am facing a problem where the images appear broken in the browser. Despite looking for solutions to similar issues, none have resolved the issue for me. Specifics In my server.t ...

Ways to transfer an Object from a service to a component

I'm currently working on my website and trying to implement a cart feature where users can add items. To achieve this, I have created a service that contains the cart as an object called cart. The service has functions to add items to the cart and ret ...

Having trouble executing the project using Gulp

I'm a beginner in front-end development and I am working on an existing project that I'm having trouble running. According to the documentation, I should run the project by executing: $ gulp && gulp serve But I keep getting this error: ...

Issue with Vue plugin syntax causing component not to load

I'm facing an issue with a Vue plugin that I have. The code for the plugin is as follows: import _Vue from "vue"; import particles from "./Particles.vue"; const VueParticles = (Vue: typeof _Vue, options: unknown) => { _Vue. ...

A function in Typescript is created to handle diverse input types in a generic manner

My goal is to create a function that can handle various input types for abstraction purposes. type ContentA = string type ContentB = number type InputA = { name: 'method_a' content: ContentA } type InputB = { name: 'method_b' con ...

Utilizing shared state in React components through props

Currently, I am utilizing a shared global state in the following manner: interface DashboardProps extends React.Props<Dashboard> { globalState? : GlobalState } export class Dashboard extends React.Component<DashboardProps, any>{ } Withi ...

Accessing external data in Angular outside of a subscription method for an observable

I am struggling to access data outside of my method using .subscribe This is the Service code that is functioning correctly: getSessionTracker(): Observable<ISessionTracker[]> { return this.http.get(this._url) .map((res: Response) => ...

Typescript raises an issue regarding a React component's optional prop potentially being undefined

I have a basic React component that looks like this: interface ComponentProperties { onClick?: () => void; } const CustomComponent = (properties: ComponentProperties) => { if (!properties.onClick) { return <></>; } ...

My goal is to prevent users from using the Backspace key within the input field

Let's say we want to prevent users from using the backspace key on an input field in this scenario. In our template, we pass the $event like so: <input (input)="onInput($event)"> Meanwhile, in our app.component.ts file, the function ...

I am a beginner in the world of Typescript/Angular, and I have encountered a compiling error TS2339. It seems that even when the condition *ngIf="x.length > 0;" should be false, the

I'm currently enrolled in a Typescript/Angular course where I am learning about the implementation of "*ngIf". During one of the lessons, the instructor provided an example using an empty array to demonstrate how it fails the condition and results in ...

What is the best way to test for errors thrown by async functions using chai or chai-as-promised?

Below is the function in question: async foo() : Promise<Object> { if(...) throw new Error } I'm wondering how I should go about testing whether the error is thrown. This is my current approach: it("checking for thrown error", asy ...

pressing the button again will yield a new outcome

I am looking to disable a button (material ui) when it is clicked for the second time by setting disabled={true}. Unfortunately, I have not been able to find any examples related to this specific scenario on StackOverflow. <Button onClick={this.s ...