Is it possible for a conditional type in TypeScript to be based on its own value?

Is it possible to use this type in TypeScript?

type Person = {
  who: string;
}

type Person = Person.who === "me" ? Person & Me : Person;

Answer №1

I believe utilizing a discriminated union might be the solution:

type Myself = {
  identity: 'myself',
  secret: string;
}

type Another = {
  identity: 'another',
}

type Individual = Myself | Another;

Answer №2

Absolutely, you have the capability to achieve this using Generics, Distributive Conditional Types and Unions.

Here is a simple example to demonstrate how it can be done:

type Somebody<T extends string> = {
    who: T;
}

type Myself = {
    me: boolean;
}

type Thatother<T extends string> = T extends 'me' ? Somebody<T> & Myself : Somebody<T>;

function identify<T extends string>(who: T) {
    return {
        who,
        me: who === 'me' ? true : undefined
    } as Thatother<T>
}

const x = identify('someone');
const y = identify('me');

x.who;  // works fine
x.me;   // shows error

y.who;  // works fine
y.me;   // also fine

Check out the TypeScript playground for a live demonstration here.

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

JavaScript and JSON interchangeably, the first AJAX response should be rewritten by the second response

I am facing an issue with my code: I have two ajax calls being made on window.load, and it seems like the response from the second AJAX call is overwriting the response from the first one before my function can process it. I'm not sure where I'm ...

Arranging items in Angular based on selection from the database

i have data in table: Id, word, score , score_list. score are 0.4, 0.2, -0.5, 0, -0.3 .... in score_list i have positive, negative , neutral. How can i sort data with select by score_list? This is html <select class="form-control"> <option> ...

Navigating over two JSON arrays using Ajax

My goal is to fetch data from a JSON file by utilizing the ID obtained from a previous AJAX call and looping through the second array based on the retrieved ID. I have attempted to achieve this with the following code: $(document).on('click', ...

What is the best way to stack col-xs-6 elements instead of having them side by side?

My form fields are currently set up using 3 col-xs-6 classes, but I'm not seeing the desired layout. I am aiming for: | col-xs-6 | | col-xs-6 | | col-xs-6 | However, what I am getting is: | col-xs-6 | col-xs-6 | | col-xs-6 | I understand that th ...

ms-card malfunctioning due to data issues

I'm facing difficulties in transferring the data to the template. Although I can access the data in HTML using vm.maquinas and maquina, I am unable to pass it to the TEMPLATE through ng-model. Information about ms-cards was not abundant. Module ang ...

Are there any debugging tools specific to Internet Explorer for JavaScript?

I need a reliable JavaScript debugger for Internet Explorer. I have tried using Firebug Lite, but it doesn't seem as detailed as the original Firebug when it comes to displaying JavaScript errors. Does anyone know how to pinpoint JavaScript errors in ...

Trouble with passing the function variable to setState efficiently

Although I haven't worked with React for a while, it seems like this issue is more related to plain JS. Here is the setState function that I am using: // click event on parent for performance reasons ``Component:`` const [active, setActive] = useSta ...

I want to use Angular and TypeScript to play a base64 encoded MP3 file

I am attempting to play a base64 encoded mp3 file in an Angular application. I have a byteArray that I convert to base64, and it seems like the byte array is not corrupted because when I convert it and paste the base64 string on StackBlitz https://stackbli ...

Issues with conditional types in TypeScript functionality not yielding desired results

Here is some TypeScript code that I am working with: type NumberOrNever<T> = T extends number ? T : never function f<T>(o: T) : NumberOrNever<T> { if (typeof o === "number") return o; throw "Not a number!" } ...

After upgrading from Vuetify version 1.5 to 2.0.18, an issue arises with modules not being found

I encountered the following error: module not found error To address this issue, I took the following steps: Commented out import 'vuetify/src/stylus/main.styl' in the src/plugins/vuetify.js file. Added import 'vuetify/src/styles/main. ...

What is the reason behind Selenium not utilizing JavaScript?

I've been a beginner in the world of Javascript for a while now, with my main goal being to use it for creating Selenium automations as part of my journey into QA automation. However, I find myself quite perplexed when it comes to the language. In al ...

Having trouble understanding why the other parts of my header are not displaying

<head> This special function runs when the webpage is loaded. <body onload="myOnload()"> A distinctive div at the top with a unique graphic <div id="header"> <img src="resumeheader.png" alt="Header" style="width:750px;h ...

What could be the reason for the initial response appearing blank?

How can I retrieve all the comments of a post using expressjs with mongodb? I am facing an issue where the first response is always empty. Below is the code snippet: const Post = require("../models/posts"), Comment= require("../model ...

Switch between selection modes in React JS DataGrid using Material UI with the click of a button

I've been working on creating a datagrid that includes a switch button to toggle between simple and multiple selection modes. const dispatch = useDispatch(); const { selectedTransaction } = useSelector(...) const [enableMultipleSelection, setEnableMu ...

The request to sign up at http://localhost:3000/api/signup resulted in a 400 (Bad Request

Having recently started working with the MEAN stack, I've run into some issues when trying to send registration data using http.post. Below is my server code: var express = require('express'), bodyParser = require('body-parser' ...

Issue encountered when trying to pass a string into URLSearchParams

const sortString = req.query.sort as string const params = Object.fromEntries(new URLSearchParams(sortString)) Upon moving to the implementation phase, I encountered: declare var URLSearchParams: { prototype: URLSearchParams; new(init?: string[][] ...

Having trouble with Angular Ng2-file-Upload's Upload.all() method not successfully sending files to the API

Dealing with the challenge of uploading files in mp4 and jpg formats, I have set up 2 separate instances of FileUploader with custom validation. Upon clicking the upload button, I attempt to merge the files from both instances into a single FileUploader ...

Personalized 404 Error Page on Repl.it

Is it possible to create a custom 404-not found page for a website built on Repl.it? I understand that typically you would access the .htaccess file if hosting it yourself, but what is the process when using Repl.it? How can I design my own 404-not found p ...

Node.js UDP broadcast to subnet not working properly in Linux

Here is a simplified Node JavaScript code snippet for testing purposes. Click here to view the code on GitHub This code creates a socket for each interface address, calculates the subnet broadcast address, and then sends data every second for 4 seconds t ...

VueJS - Input Image Display Issue Causing Browser Slowdown

I'm experiencing some issues with my VueJS component that includes a file input and displays an image afterwards. Strangely, this is causing my web browsers (both Firefox and Chromium) to freeze up and use massive amounts of CPU. I tried switching to ...