Type '...' does not contain the specified conditional generic property '...'

TypeScript Playground

type Foo<BooleanParameter extends boolean> = { boolean_parameter: BooleanParameter } & (BooleanParameter extends true ? { first_parameter: number } : { second_parameter: string })

const bar = <BooleanParameter extends boolean>(foo: Foo<BooleanParameter>) => {
    if (foo.boolean_parameter) {
        //foo.first_parameter Property 'first_parameter' does not exist on type 'Foo<BooleanParameter>'.
    } else {
        //foo.second_parameter Property 'second_parameter' does not exist on type 'Foo<BooleanParameter>'.
    }
}

What is the reason behind the inability to access first_parameter and second_parameter when boolean_parameter is generic?

Answer №1

Is this solution suitable for your needs?

type TrueBoolean = { boolean_parameter: true } & { first_parameter: number };
type FalseBoolean = { boolean_parameter: false } & { second_parameter: string };

type Foo<B extends boolean> = B extends true ? TrueBoolean : FalseBoolean;

const bar = <B extends boolean>(foo: Foo<B>) => {
  if (foo.boolean_parameter) {
    return foo.first_parameter;
  } else {
    return foo.second_parameter;
  }
}

const f: Foo<boolean> = { boolean_parameter: true, first_parameter: 20 };
bar(f); // successful execution

const g: Foo<boolean> = { boolean_parameter: false, second_parameter: "20" };
bar(g); // successful execution

// const h: Foo<boolean> = { boolean_parameter: true, second_parameter: "3" }; // Error, Object literal may only specify known properties, and 'second_parameter' does not exist in type 'TrueBoolean'
// const i: Foo<boolean> = { boolean_parameter: false, first_parameter: 3 }; // Error, Object literal may only specify known properties, and 'first_parameter' does not exist in type 'FalseBoolean'

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

Why am I encountering the 'nonexistent type' error in my Vue 3 project that uses Typescript and Vuelidate?

Seeking assistance with a Vue 3 and Vuelidate issue. I followed the configuration guide provided at . <script lang="ts"> import { required, minLength, maxLength, numeric } from '@vuelidate/validators' import useVuelidate from &apo ...

Tips for invoking an Android function from an AngularJS directive?

I am facing an issue with my HTML that uses an AngularJS directive. This HTML file is being used in an Android WebView, and I want to be able to call an Android method from this directive (Learn how to call Android method from JS here). Below is the code ...

Utilize React to iterate through data retrieved from firebase

I'm currently facing an issue with Google Firebase Realtime database where I am unable to create an array of the collection. Whenever I loop through the const return in console log, I receive messages as individual objects. However, what I actually n ...

Adding additional properties to Material UI shadows in Typescript is a simple process that can enhance the visual

https://i.stack.imgur.com/9aI0F.pngI'm currently attempting to modify the Material UI types for shadows, but encountering the following error when implementing it in my code. There is no element at index 25 in the tuple type Shadows of length 25. I&a ...

How can you keep TypeScript satisfied when extending classes that come from 'node modules'?

Update: Included ARTICLES_QUERY, tsconfig.json, and package.json as requested. Update 2: The current solution is functional, but it doesn't seem ideal. Any suggestions for improvement would be appreciated. export default class InterfaceGraphQLApi ex ...

What is the correct way to convert a non-observable into an observable?

Can I convert a non-observable into an observable to receive direct image updates without having to refresh the page, but encountering this error: Type 'EntityImage[]' is missing the following properties from type 'Observable<EntityImage ...

"Encountering an error searching for the chai module in the node modules folder even though

Attempting to install chai through the command line, I used the following command. npm install --save-dev chai After that, I attempted to run my unit test class with the specified imports: import {assert} from 'chai'; import {expect} from &ap ...

A guide on transferring received data from dataService within the parent component to the child component in Angular2

Within the context of my application, there exists a parent component named app-parent and a child component called app-child. In app-parent, I retrieve data from a DataService. @Component({ selector: 'app-parent', providers: [DataService] ...

Is there a way to invoke a client-side function from the server?

Is there a way to display an alert at the top of the browser if the SQL query returns empty results? I tried using the "alert" function, but I'm struggling with customizing its appearance. I have a function in my HTML code that triggers an alert, but ...

Having trouble rendering a Twitter timeline on an Angular 7 project

I am attempting to embed a Twitter timeline in an Angular page by following the instructions outlined at . However, I am encountering an issue where only the button renders and not the actual timeline itself. The code in my index.html file is as follows: ...

What are the steps for executing operations on a combined array of different data types?

This code snippet is not functioning as expected type Foo = number[] type Bar = string[] function move(x: Foo | Bar) { const v = x.splice(0, 1) x.splice(1, 0, ...v) } The issue arises because v is inferred to be of type number[] | string[], which ...

After the assignment, TypeScript reordered the elements of the array

Dealing with an array of objects for use in a ngFor loop has presented a challenge. The issue arises when the order that was initially set for the array changes unexpectedly due to JavaScript manipulation. Originally, the array is ordered as expected when ...

Similar to the "beforesend" functionality in JavaScript, there is a corresponding feature

When attempting to post a comment in my ionic app using the Wordpress api, I encountered error 401 (unauthorized) indicating that the Wordpress api does not recognize me as logged in. This is the code I am using: postComment(params?: any) { let nonce = l ...

Possible undefined object in React Redux

I'm encountering a Typescript issue where Redux object I am utilizing is potentially undefined, even though I have not specified its type as potentially being undefined or set it to be undefined anywhere in my code. /redux/globalSettings/actions.ts ...

Angular error: Trying to access the sort property of an undefined value

I am currently working on creating a sorting function and pipe for a table. I found guidance on how to do this by following a tutorial at this link, and here is the plunker example. In the example, the table header should be clickable to trigger the sort() ...

Performing Jasmine unit testing on a component that relies on data from a service, which itself retrieves data from another service within an Angular 2+ application

Attempting to implement unit testing for a service using httpmock has been challenging. The service in question utilizes a method to make http get calls, but I have encountered difficulties in writing the test cases. saveservice.service.ts -- file const ...

Disabling the Angular router link

I'm currently working on an Angular application that utilizes routing and auth guards. Check out the code on StackBlitz View the app component HTML here <div class="container"> <div class="row"> <div class="col-xs-12 col-sm-10 ...

Guide to creating a constants file in Node.js

Currently working on creating a constants file in nodejs, but encountering an issue: ERROR in src/app/esri-map/sti/sti-layers-urls.ts(1,1): error TS2304: Cannot find name 'module'. Here is the content of the constants file (sti-layers-urls.ts): ...

Injecting a useFactory provider in Angular is a common practice

I manage a factory provider service that selects a service based on a flag. Everything works fine when I need a debug students service, but when I set the flag to false, the application throws an ERROR TypeError: serverService.fetchData is not a function. ...

Differentiating AWS API errors in TypeScript: A guide

How can I write different handlers in TypeScript for ThrottlingException and ExecutionLimitExceeded when starting a StepFunction execution? new StepFunction.startExecution({}, (err, data) => { if (err) { // Need to identify ThrottlingExcepti ...