What steps can be taken to address a TypeScript error when a function's parameters may be of two different types?

I'm facing an issue with a simple function that retrieves the address as a string

interface AddressType1 {
  city: string | null; 
  state: string | null;
  postalCode: string | null;
}

interface AddressType2 {
  city: string | null; 
  region: string | null;
  postalCode: string | null;
}

export const getAddressString = (
  address: AddressType1 | AddressType2 | null,
): string => {
  if (address != null) {
    return `${address.city ?? ""}, ${address.region ?? address.state ?? ""} ${address.postalCode ?? ""}`;
  }
  return "";
};

However, TypeScript is throwing an error stating

Property 'region' does not exist on type 'RoadsideLocation'
and
Property 'state' does not exist on type 'LocationGeocodedAddress'
.

Answer №1

Are you searching for the intersection symbol, &, in programming?

  Example: ( TypeA & TypeB )| null,

Answer №2

Consider the following scenario:

interface LocationType1 {
    city: string | null;
    state: string | null;
    postalCode: string | null;
}

interface LocationType2 {
    city: string | null;
    region: string | null;
    postalCode: string | null;
}

type AddressUnion = LocationType1 | LocationType2

const hasPropertyCheck = <Obj, Prop extends string>(obj: Obj, prop: Prop)
    : obj is Obj & Record<Prop, unknown> =>
    Object.prototype.hasOwnProperty.call(obj, prop);

const checkIfType1 = (location: AddressUnion): location is LocationType1 => hasPropertyCheck(location, 'region');

type PossiblyNull<T> = null | T

const isNullOrNot = (str: PossiblyNull<string>): str is null => str === null

const generateAddressString = (city: PossiblyNull<string>, postalCode: PossiblyNull<string>) => (stateRegion: PossiblyNull<string>) =>
    [city, stateRegion, postalCode].reduce<string>((acc, elem) => isNullOrNot(elem) ? acc : `${acc},${elem}`, '');

export const createFormattedAddress = (
    location: AddressUnion,
) => {
    const { city, postalCode } = location;
    const partialResult = generateAddressString(city, postalCode)

    if (checkIfType1(location)) {
        return partialResult(location.state)


    }
    return partialResult(location.region)

}

Avoid invoking the function when the argument is null.

generateAddressString involves partial application.

If dealing with a union, consider using typeguards

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

Unlock the key to connecting the output of one observable to another in rxjs

I have a procedure for saving users in the database. These are the steps I take: 1) First, I validate the request. 2) Next, I hash the password. 3) Finally, I store the user details in the users collection along with the hashed password. Below is the ...

Error: AJAX response shows as NaN, indicating that the requested resource was not found

Attempting to create a search engine using AJAX. When typing in the search box, nothing happens. After inspecting the element and opening the console, an error message is displayed: script.js:19 GET http://localhost/var/www/html/pendaftaran-siswa/NaN 404 ( ...

The code snippet contained within the Highlight component is rendered in a continuous, unbroken line

The code snippet within the Highlight component is currently displaying as one long single line. Is there a way to include multiple lines of code within the Highlight component? ...

Is there a way to extract the text that lies between two closed HTML

Looking for a solution using jQuery. <pre><marker id="markerStart"></marker> aaaaa <span style='font-family:monospace;background-color:#a0a0a0;'>bbb</span>bb cc<marker id="markerEnd"></marker>ccc </pr ...

What is the best way to set up prettier in VSCODE so that it organizes jsx attributes across multiple lines?

My preference is for the following syntax: <input id="inputForEmail" type="email" className="form-control" aria-describedby="Enter email address" placeholder="Enter emai ...

struggling to determine the connection status between tables (Many-to-many or one-to-one)

Seeking assistance: I am working with two tables (member, event) where each member attends multiple events and each event has multiple attendees. Do these relationships represent a many-to-many or one-to-one relationship? ...

What are the steps for sending a POST request with custom headers?

Currently, I am attempting to make a post request: For this request, I require a body that looks like this: { "listSearchFields": { "email": "sample" } } When testing this in Postman, it works fine. However, when trying to implement this code in ...

What is the best way to limit the length of text in a div if it surpasses a

As I work on a website, users have the ability to add headings to different sections of a page. For example: M11-001 - loss of container and goods from Manchester Some headings can be quite detailed, but in reality, only the first few words are needed to ...

Error encountered when attempting to display a particular user with a specific _id in MongoDB, Node, and React: Failed to convert value "undefined" to ObjectId in the "user" model

I am experiencing an issue on my page where multiple users are displayed. Whenever I click on a user, it should redirect me to their individual page, but instead, I encounter the following error: Cast to ObjectId failed for value "undefined" at path "_id" ...

View real-time data in Vuejs 3 as it executes

I am currently working on a form that populates a table with data retrieved from a Laravel API. I am using Vue.js 3 and Composition API to build my entire application. When the button is clicked, I want the table to be filled with data from the form. The b ...

Error message encountered: ReferenceError - The subcommand specified in Discord.js Slash Command function is undefined

I have been experimenting with subcommands in a slash command for a discord bot. I plan to have several similar subcommands, so I wanted to create a function that can be called within .addSubCommand, but it seems like it's not functioning correctly. ...

Adding elements to an array in Node.js

In my 'both' object, I need to store 2 arrays: eng and fr. Each of these arrays contains multiple objects. How can I transfer all values from frDisplayData to fr:[] within the 'both' object: const displayData = []; var both = {eng:dis ...

modified a file using express framework

I am attempting to utilize mongoDB in order to update the status of an existing document. Despite my backend successfully receiving the routes, the mongoDB update process is not functioning as expected. router.post('/orders_drivers', function (r ...

Ensure that you wait for all asynchronous $http requests to finish in AngularJS before continuing

I am facing a challenge with a page that generates a varying number of $http requests based on the length of a certain variable. I aim to update the scope with the data only after all requests have been completed. Without relying on jQuery for this project ...

I am interested in extracting information from the Firebase real-time database and showcasing it on my HTML webpage

I am struggling to display data from the Firebase real-time database on my HTML page. Even though I can see all the data perfectly in the console, it doesn't show up on the webpage. I attempted to use a for loop, but it still doesn't display the ...

How can we use JavaScript to close a dropdown menu when the user clicks outside of it?

I am facing an issue with my code. I want to close the dropdown menu when clicking outside of it or on the items within the dropdown. How can I achieve this? I attempted to use addEventListener('click', myFunction) on `document` but it did not w ...

Transmitting information from the front-end Fetch to the back-end server

In my stack, I am using Nodejs, Express, MySQL, body-parser, and EJS. My goal is to trigger a PUT request that will update the counter by 1 when a button is pressed. The idea is to pass the ID of the clicked button to increment it by 1. app.put("/too ...

Automatically adjusting the locale settings upon importing the data

Is there a way to create a dropdown menu of languages where clicking on one language will change the date format on the page to match that country's format? In my React app, I am using moment.js to achieve this. My plan is to call moment.locale( lang ...

Using an AngularJS ng-repeat alias expression with multiple filters

As stated in the Angular ngRepeat documentation, the alias expression can only be used at the end of the ngRepeat: It's important to note that `as [variable name]` is not an operator, but rather a part of the ngRepeat micro-syntax and must be place ...

Determining the necessary data to send via ajax for a particular issue

Currently, I am learning JavaScript and have encountered another challenge along the way. I am looking for assistance in understanding the concept, whether it is a solution in jQuery or Angular. I have two types of tasks in my HTML - audio or graphic. The ...