Special or specific types in typescript

I am trying to create a TypeScript function that accepts an argument matching one of two conditions:

type A = {
  x: string
}

type B = {
 y: string
}

function testFunc(param: A | B) {
  ...
}

However, TypeScript allows me to call the function with both keys:

testFunc({x: "x", y: "y"})

Shouldn't the union type restrict the function to only accept either A or B?

Playground showcasing the issue here

Answer №1

To achieve this, you can utilize function overloads:

type First = {
    a: string
}

type Second = {
    b: string
}


function check(inputs: First): void;
function check(inputs: Second): void;
function check(inputs: (First | Second)) {
    console.log(inputs)
}

check({
    a: 'x',
}) // successful

check({
    b: 'm'
}) // successful

check({
    a: 'x',
    b: 'm'
}) // error

Check it out in the 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

Exploring an Angular Real-World Example Application on Github - Resolving the Following Bug

my surroundings. export const environment = { production: false, api_url: 'localhost:3306/api' }; my personal server is at localhost:3306 (MAMP) The instructions provided are to edit src/environments/environment.ts in order to ch ...

Ensuring correct association of values to avoid redundancies

There are 5 fields available for users to fill out on this form: Leave Code, From Date, Input Time1, To Date, and Input Time2. These variables are declared as a dates object in the .ts file, as shown below. interface Supervisor { name: string; code: s ...

There has been no answer provided. Could this be due to being utilized in an asynchronous function that was not returned as a promise?

I encountered the following error message: Error: No response has been set. Is this being used in an async call that was not returned as a promise to the intent handler? at DialogflowConversation.response (/user_code/node_modules/actions-on-google/dis ...

Typescript: organizing nested types within an interface

My goal is to create an interface CountersData based on my JSON data. The challenge lies in the nested id property, which contains an array of nested dictionaries. I want this property to be optional. However, I have not been successful in making it option ...

Discovering duplicates for properties within an array of objects in React.js and assigning a sequential number to that specific field

I am working with an array of objects where each object contains information like this: const myArr=[{name:"john",id:1}{name:"john",id:2}{name:"mary",id:3}] In the first 2 elements, the "name" property has duplicates with the value "john". How can I updat ...

Are there any other methods besides @ViewChild to access template elements by template ID in Angular v4.3.3?

In the past, using @ViewChild('#templateId') was an accepted method for obtaining an Element Reference. @ViewChild('#templateId') elementName: ElementRef; However, it appears that this is no longer a viable approach as @ViewChild now ...

Capturing user audio on the client side with Angular

Is there a built-in feature in Angular to record client-side audio input? I have attempted using the p5 library, but it is encountering integration problems. ...

Encountering a Prettier error with React Native 0.71 and Typescript

https://i.stack.imgur.com/h9v5X.pngThe app runs smoothly, but these red warnings are really bothering me. How can I resolve this issue?https://i.stack.imgur.com/NebzJ.png ...

The "npx prisma db seed" command encountered an issue: Exit code 1 error occurred during the execution of the command: ts-node --compiler-options {"module":"CommonJS"} prisma/seed.ts

this is a sample package.json file when I try to execute the command "npx prisma db seed", I encounter the following error: An error occurred while running the seed command: Error: Command failed with exit code 1: ts-node --compiler-options {&qu ...

How to implement a Typescript interface without necessarily implementing the parent interfaces

Within my current project, I have defined the following interfaces: interface foo { fooProperty: number; fooFunction(): void; } interface bar extends foo { barProperty: string; barFunction(): void; } Now, I am interested in creating a class like ...

Execute webpack with no production bundling

When attempting to create a development build (by setting DEV = true), everything runs smoothly. However, when I try to generate a production build, the bundle does not show up in the js folder. Interestingly, I found that if I replace my application with ...

What are the benefits of utilizing TypeScript declarations? How can you demonstrate their value with concrete examples?

I'm a bit confused about the use of declaration in TypeScript. It seems like the compiler doesn't compile it into the js file, so what is the purpose and advantage of using declaration? Can someone please explain this to me? ...

Steps for converting an array of objects to a different array of objects in TypeScript

Is there a way to transform an array of objects into another array of objects in TypeScript? a : [ {bcdbcd : 1, abcabc : "value1"}, {bcdbcd : 2, abcabc : "value2"}, {bcdbcd : 3, abcabc : "value3"} ] a : [ {label: 1, ...

What is the best way to implement event handling for multi-level components/templates in Angular 5?

Currently, I am immersed in a project using Angular 5. One of the templates, called Template A, is filled with various HTML elements. I am incorporating Template A into another template, Template B, which offers additional functionalities on top of Templat ...

The React component was not able to receive any children as input

My Typescript-written React component is called GradientText.tsx: import React, { ReactNode } from "react" import { cn } from "@/lib/utils" const typeMap = { h1: "h1", h2: "h2", p: "p", } inte ...

What is the best way to link the data from the HTML input to the class property in the TypeScript file? (Combining Angular and IntroJs)

I'm working on an onboarding screen with Intro.js and need help with receiving user input. I've been trying different methods like [(ngModel)] = checked, [(checked)] = checked, (checked) = checked, but haven't had any success. Can anyone pro ...

Encountering IntelliSense error in VSCode while attempting to assign a method to an interface

When I use intellisense with the following code snippet, everything works perfectly: test.d.ts: export interface ITest { foo: string; setFoo(foo: string): ITest; } export as namespace JSDoc; test.js: /** @typeof {import("./test")} JSDoc */ /* ...

"Sequencing http.get requests in Angular 2 using

In my service, I have a series of http.get requests structured as follows: constructor(private http:Http) {} getDetails(sysID:string){ var details; this.http.get('https://blahURL').map(res => res.json().filter(f => f.id == another.id)[0] ...

Unable to update markers on agm-map for dynamic display

In my Angular 5 application, I am utilizing Angular Google Maps (https://angular-maps.com/) along with socket.io for real-time data updates of latitude and longitude from the server. Although I am successfully pushing the updated data to an array in the co ...

Angular 6: Harnessing the Power of RouterLinks

Can you navigate to a different section of another page using the defined ID without having to reload the entire page? ...