A TypeScript utility designed to manage object types that may or may not be

Is there a way in TypeScript to define a function, findUser, that can take either a username (as a string) or a user_id as a number?

function findUser(info: {user_id: number} | {username: string}) {
  if (info.user_id) {

  }
  if (info.username) {

  }
}

I am encountering a TypeScript error on the info.user_id because the user_id field is not guaranteed to exist on info.

An alternative approach would be to define the function like this:

function findUser(info: {user_id?: number; username?: string}) {

This works, but it allows passing an empty object. I want a way to check against this.

(I have a more complex scenario with 4 types of inputs. Once I solve this simpler example, I believe I can handle the more complicated one.)

So my question is: Can TypeScript support something similar to the first function definition?

Answer №1

In order to properly define both alternatives, they need to be specified as a type:

  type UserInfo = { user_id: number; username?: string; } | { user_id?: number; username: string };

  function findUser(info: UserInfo ) {

It's important to note that by using this method, you are allowing for the provision of both user_id and username. If this is not the desired outcome, you can utilize the never type:

  type UserInfo = { user_id: number; username?: never; } | { user_id?: never; username: string };

  function findUser(info: UserInfo ) {

Answer №2

Implementing interfaces or utilizing a quick method is a viable approach

const findUser: { (name: string) : void; (Id: number): void; } = (value: string | number): void => {
if (typeof value === typeof 'string') { console.log("find by name") }

Answer №3

I prefer to approach it in this manner

interface PropsName {
  username: string
  userId?: string
}

interface PropsID {
  userId: string
  username?: string
}

function searchUser(details: PropsName | PropsID) {
  if (details.userId) {
    
  }
  if (details.username) {

  }
}

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

The computed function is unable to find the property on the specified type

I am a beginner in TypeScript. I have encountered an issue with the code below, which runs perfectly fine in JavaScript but is not compiling here. export default { data: function() { return { data: [ 'Angular', 'A ...

"Unlocking the power of Express.js and Node.js: Leveraging variables within the scope of every request

In my node.js express application, I am facing a challenge with setting a language variable that determines the language for each data request. 1) I need to access this language variable across all files within the scope of a particular request. 2) It is ...

Typescript: Understanding the question mark usage on arrays

In this example, I have the basic structure of my code: let myArray: (Array<any> | null); if (cnd) { myArray = []; myArray?.push(elt); // Curious about this line myArray[0].key = value; // Questioning this line } else { myArray = null; } Wh ...

Ways to fetch data based on a specific relationship criterion

In my data structure, there is a Product entity and an Image entity with a OneToMany relationship. This means that One Product can have many Images attached to it. When an image needs to be removed, instead of deleting the data from the table, I have chos ...

Karma keeps showing up as empty coverage

I've been struggling to get karma coverage to work for the past couple of days, but all I keep seeing is a blank empty page like this: https://i.sstatic.net/3Fr6I.png Check out my configuration: var path = require('path'); var webpackCon ...

What is the method to retrieve Response Headers in cases of an empty response?

Currently, I am working with Angular2 and dotcms. My goal is to retrieve response headers after making a call to subscribe. const httpOptions = { headers: new HttpHeaders({ 'Content-Type': 'application/json' }) .append('Access ...

Angular 7 ESRI loader search widget focus out bug: finding a solution

I am currently working on implementing an ESRI map using esri-loader in my Angular application. Everything seems to be working fine, but I am encountering an error when typing something into the search widget and then focusing out of it. "Uncaught Typ ...

I'm facing issues with the angular-stl-model-viewer in my current Angular project

I recently attempted to incorporate an stl-viewer into my Angular project using the npm package angular-stl-model-viewer and managed to install all necessary dependencies without any issues. However, I encountered a problem where the viewer is not displayi ...

Angular ERROR: Trying to access rating property of an undefined value

I'm encountering an issue on a website where users can vote for their favorite animal. Whenever I try to select an animal to vote for, I receive an unclear error message that has been difficult to resolve even after searching online for a solution. A ...

Implementing Code-Prettify in Angular 4 with Typescript

Recently, I've been delving into the world of Typescript and Angular 4. One challenge I'm facing is integrating Google Code-Prettify with my angular CLI setup. I'm currently attempting to understand how to import code-prettify dynamically f ...

Exclude the bundled .d.ts files and opt for external declarations instead

I am endeavoring to implement the validate.js library, which comes with its own TypeScript declaration file. However, the provided typing for the library is not very accurate, and there is a more superior one available in DefinitelyTyped. Despite installi ...

Ways to bring attention to a bootstrap card when it is clicked

I'm a beginner with bootstrap and we have a set of cards that we want to highlight when clicked. The structure of the cards is as follows: <div class="container"> <div class="row"> <div class="card"> <div ...

Encountering TS7053 error while trying to access component variables using type indexing in Angular 13

When trying to access a variable with type indexing in Angular 13, I encountered a TS7053 error. However, in this Stackblitz example, the same code works without any errors. export class AppComponent { name = 'Angular ' + VERSION.major; Pro ...

Tips for eliminating a single occurrence with Array.prototype.filter()

I am facing an issue in my React app with the deleteNumberFromList method. This function is designed to remove a specific number from the array by utilizing a setter hook: const [valuesList, setValuesList] = useState<number[]>([]); const deleteNumbe ...

How to efficiently upload multiple files simultaneously in Angular 10 and .NET Core 5 by utilizing a JSON object

I have a JSON object structured like this: Class->Students this is a basic representation of my TypeScript class export class Classroom { Id:number; Name:string; Students:Student[]=[]; } export class Student { Name:string; Age:number; Sex:string; Imag ...

Error message: "Angular requires either importing or local installation"

For my ionic application development, I encountered an issue while trying to link pages together in the ionic creator. The error message on the .ts file is: typescript: src/pages/home/home.ts, line: 4 Individual declarations in merged declar ...

Guide on implementing the Translate service pipe in Angular 2 code

So here's the issue... I've integrated an Angular 4 template into my application which includes a functioning translate service. The only problem is, I'm unsure of how to utilize that pipe in my code. In HTML, it's as simple as adding ...

Steps for setting up Protractor Cucumber Report with TypeScript and screenshots:

I've searched for many tutorials on setting up Protractor with Cucumber reports and screenshots in TypeScript, but have had no luck. Can you provide assistance in configuring this? ...

The animation in ThreeJs encounters context issues within Angular 2

I am trying to incorporate ThreeJs into my Angular 2 project. I have successfully rendered a scene with a simple cube, but I ran into an issue when using the animate() function. Here is the code snippet: import { OnInit, Component } from '@angular/co ...

I am having trouble getting debugging with source maps to work in VSCode and Browserify

I'm currently experiencing an issue with setting breakpoints in Chrome using VSCode, especially when working with TypeScript and Browserify. Oddly enough, if I open Chrome separately and manually refresh the page, the source maps load correctly and I ...