Using Typescript to create a generic return type that is determined by the type of a property within an object union

Consider the following scenario:

type Setting = {
    key: "option_one",
    value: number,
} | {
    key: "option_two",
    value: string,
}

export type SettingKey = Setting["key"];
// "option_one"|"option_two"

How can we develop a function to handle this situation?

function getSettingValue(key: SettingKey) /* : return type based on key*/ {
    const setting: Setting = this.database.getSettingByKey(key);
    return setting.value;
}

When trying to assign a new object with the Setting type, TypeScript correctly identifies that assigning a string value when the key is option_one is an error.

const setting: Setting = {
    key: "option_one",
    value: "invalid input" // Error: Type 'string' is not assignable to type 'number'
};

Therefore, it should be possible to derive the specific data type of the value property inside the Setting object and utilize it as the return type for the function.

Is there a way to enforce the return type of the getSettingValue function to be determined by the provided SettingKey? Potentially utilizing generics rather than a generic number|string return type.

Answer №1

One possible solution is to utilize the Extract method in this scenario:

function retrieveConfig<K extends ConfigKey>(key: K): Extract<Config, { key: K }>["value"] {
  // Implementation goes here...
}

This function will filter out all elements in Config that match the criteria of being assignable to { key: K }, and then return the value type of those elements.

Link to Playground

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 changes can be implemented to convert this function to an asynchronous one?

Is it possible to convert the following function into an asynchronous function? getHandledSheet(): void { this.timesheetService.getAllTimesheets().subscribe({next: (response: TimeSheet[]) => {this.timesheetsHandled = response.filter(sheet => ...

The module 'Express' does not have a public member named 'SessionData' available for export

I am encountering an issue while working on my TypeScript project. I am not sure where the error is originating from, especially since nothing has been changed since the last time I worked on it. node_modules/connect-mongo/src/types.d.ts:113:66 - error TS ...

Error: Idle provider not found in the promise

Currently, I am integrating ng2-idle into an AngularJS 2 application. After successfully including the ng2-idle package in the node_modules directory of my project, I attempted to import it into one of my components as shown below: Dashboard.component.ts: ...

NG0900: Issue encountered while attempting to compare '[object Object]'. Please note that only arrays and iterable objects are permitted for comparison

Experimenting with an Angular project where I am retrieving data from a Minecraft API and displaying it on my website. This is my first time working with Angular's HTTP requests. Encountered the following error code; NG0900: Error trying to diff &apo ...

Comparing TypeScript and C++ in terms of defining class reference member variables

class B; class A { A(B b_) : b{b_} {} B &b; }; In C++, it is possible to have a reference member variable like 'b' in class A. Can the same be achieved in TypeScript? Alternatively, is there a specific method to accomplish this in ...

Is there a way to display the input value from an on-screen keyboard in an Angular application?

I have included my code and output snippet below. Is there a better way to display the input value when clicking on the virtual keyboard? ...

What seems to be the issue with the useState hook in my React application - is it not functioning as

Currently, I am engrossed in a project where I am crafting a Select component using a newfound design pattern. The execution looks flawless, but there seems to be an issue as the useState function doesn't seem to be functioning properly. As a newcomer ...

Unable to generate paths in Ionic 3

I am trying to view the actual route on the URL, but I'm having trouble figuring out exactly what needs to be changed. I've been referring to the documentation at: https://ionicframework.com/docs/api/navigation/IonicPage/ However, I keep encoun ...

Material UI Error TS1128: Expected declaration or statement for ButtonUnstyledProps

While working on my application that utilizes Material UI, I encountered an issue. I keep receiving a Typescript error and haven't been able to find a solution for it. TypeScript error in C:/.../node_modules/@mui/base/ButtonUnstyled/index.d.ts(3,1): D ...

Error: Unable to access the 'filter' property as it is undefined. TypeError occurred

findLoads(){ if(this.loggedInUser.userFullySetupFlag === 0 || this.loggedInUser.businessFullySetupFlag === 0){ swal( 'Incomplete Profile', 'To find loads and bid, all the details inside User Profile (My Profile) and Business Profil ...

What could be causing the QullJS delta to display in a nonsensical sequence?

The outcome showcased in the delta appears as: {"ops":[{"retain":710},{"insert":" yesterday, and she says—”\n“The clinic?","attributes":{"prediction":"prediction"}},{"del ...

Is it possible to easily organize a TypeScript dictionary in a straightforward manner?

My typescript dictionary is filled with code. var dictionaryOfScores: {[id: string]: number } = {}; Now that it's populated, I want to sort it based on the value (number). Since the dictionary could be quite large, I'm looking for an in-place ...

Using Typescript: A guide on including imported images in the output directory

typings/index.d.ts declare module "*.svg"; declare module "*.png"; declare module "*.jpg"; tsconfig.json { "compilerOptions": { "module": "commonjs", "target": "es5", "declaration": true, "outDir": "./dist" }, ...

I am looking to update my table once I have closed the modal in Angular

I am facing an issue with refreshing the table in my component using the following function: this._empresaService.getAllEnterprisePaginated(1);. This function is located in my service, specifically in the modal service of the enterprise component. CODE fo ...

Having trouble loading a lazy component in Vue3 with v-if condition?

The code is quite simple. However, I am facing an issue where the about component cannot be rendered. <template> <div id="nav"> <button @click="sh = !sh">{{ sh }}</button> <p v-if="sh">v ...

What could be causing the content in my select box to change only when additional select boxes are introduced?

When working with a form in next.js and using select boxes from material UI, I encountered an issue. The number of select boxes should change based on user input, but when I modify the value inside a select box, the displayed text does not update until I a ...

What is the best approach to creating customizable modules in Angular2?

I'm exploring the most effective approach to configuring modules in Angular 2. In Angular 1, this was typically achieved through providers. As providers have been altered significantly, what is the preferred method for passing configuration parameters ...

Issue with obtaining access token in Angular 8 authentication flow with Code Flow

As I work on implementing SSO login in my code, I encounter a recurring issue. Within my app.module.ts, there is an auth.service provided inside an app initializer. Upon hitting the necessary service and capturing the code from the URL, I proceed to send a ...

Cluster multiple data types separately using the Google Maps JavaScript API v3

I am looking to implement MarkerClusterer with multiple markers of various types and cluster them separately based on their type. Specifically, I want to cluster markers of type X only with other markers of type X, and markers of type Y with other markers ...

The server in Angular 4 does not pause for the http call to finish before rendering. This can result in faster loading

After implementing angular universal, I was able to render the static part of HTML via server-side rendering. However, I encountered an issue where API calls were being made and the server rendered the HTML without waiting for the HTTP call to complete. As ...