Error in Typescript: The property 'a' is not defined in the type 'A'

Here is an example of the different types I am working with:

type Place = {
   address: string
}

type Location = {
   latLng: string
}

type User = {
  name: string
} & (Place | Location)

When attempting to parse the data using this structure, I encounter a TypeScript error:

const { name, address, latLng } = user;

The error message states 'Property 'address' does not exist on type 'User'.

I understand that either 'address' or 'latLng' will be present but not both, and my logic will validate this when parsing the data. How can I inform TypeScript about this to remove the error?

Answer №1

Utilizing the never keyword in this scenario is a smart way to establish two distinct "configurations" for the User entity - one with a Place attribute and another with a Loc attribute. The Place type mandates an unspecified latLng property, whereas the Loc type requires an undefined address property. A User can be described as ({name: string} & Place) | ({name: string} & Loc), meaning that while all three fields exist in both Place and Loc types within the union, either address or latLng will remain undefined based on the presence of the other.

type Place = {
  address: string;
  latLng?: never;
};

type Loc = {
  latLng: string;
  address?: never;
};

type User = {
  name: string;
} & (Place | Loc);

function test1() {
  // Valid, latLng is undefined
  const user: User = { name: "User", address: "1234 Somewhere St" };
  const { address, latLng, name } = user;
}

function test2() {
  // Valid, address is undefined
  const user: User = { name: "User", latLng: "123,456" };
  const { address, latLng, name } = user;
}

function test3() {
  // Invalid, both address and latLng are present
  const user: User = {
    name: "User",
    latLng: "123,456",
    address: "1234 Somewhere St",
  };
  const { address, latLng, name } = user;
}

(Playground link)

This approach defines a type where either address or latLng can be specified but not both. By deconstructing the values from the user object, you can access both properties, with one always being undefined.

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

Transform data into JSON format using the stringify method

I am facing an issue with my TypeScript code where I need to retrieve specific information from a response. Specifically, I want to output the values of internalCompanyCode and timestamp. The Problem: An error is occurring due to an implicit 'any&apo ...

Error in vue3 with typescript: unable to assign a ComputeRef<number[]> argument to an iterable<number> in d3.js

This code snippet was originally sourced from an example at https://medium.com/@lambrospd/5-simple-rules-to-data-visualization-with-vue-js-and-d3-js-f6b2bd6a1d40 I attempted to adapt the example to a TypeScript/Vue 3 version, and below is my implementatio ...

Saving a local JSON file in Angular 5 using Typescript

I am currently working on developing a local app for personal use, and I want to store all data locally in JSON format. I have created a Posts Interface and an array with the following data structure: this.p = [{ posts:{ id: 'hey man&ap ...

Tips for showing the upcoming week in an angular application

Could someone please assist me with displaying the dates for the next 7 days using TypeScript? I am familiar with obtaining the date for the 7th day ahead, but I am unsure on how to generate a list of the 7 consecutive days. ...

What is the method to retrieve the data type of the initial element within an array?

Within my array, there are different types of items: const x = ['y', 2, true]; I am trying to determine the type of the first element (which is a string in this case because 'y' is a string). I experimented with 3 approaches: I rec ...

The TypeScript variable is automatically assigned the type 'any' since it does not contain a specified type annotation

Issue: The variable 'environment' is implicitly assigned the type 'any' because it lacks a specific type annotation and is referenced within its own initialization code. Code Snippet: export const environment = { production: fals ...

Define a distinct routing parameter that can be accessed through the ActivatedRoute instance

While working on setting up a router in my application, I encountered the need to define a query parameter that must be retrievable through the ActivatedRoute for compatibility reasons. Recently, I had to create some new sub-routes that do not follow the s ...

After using apt to install tsc, I find myself in a dilemma on how to either delete or upgrade it

After realizing I was missing Typescript on my server, I attempted to run the 'tsc' command. However, I received a message suggesting I use 'apt install tsc' instead. Without much thought, I executed the command. Normally, I would insta ...

Types are not appearing in @types/node

I have added @types/node to my project. In the index.ts file, the default node modules are being treated as type any. const fs = require('fs'); The type of fs is currently set to any. { "ts-node": { "cwd": "/User ...

Node_modules seem to be missing

After completing the TypeScript 101 QuickStart tutorial using Visual Studio 2015 and Node Tools for Visual Studio, I attempted to import the 'winston' npm module. However, no matter what path I specify, Visual Studio indicates that it cannot loca ...

When faced with the error message "Typescript property does not exist on union type" it becomes difficult to assess the variable

This question is a continuation of the previous discussion on Typescript property does not exist on union type. One solution suggested was to utilize the in operator to evaluate objects within the union. Here's an example: type Obj1 = { message: stri ...

Sources of the TypeScript library in WebStorm

I'm brand new to TypeScript. I decided to use WebStorm because I'm familiar with JetBrains tools. In other programming languages, I'm used to having a workflow that includes some kind of dependency management system like Maven, which allows ...

I'm puzzled as to why my createDoorMethod is returning a string value instead of a number, even though I am passing it a number. Can someone help me

Currently enrolled in a web development course, I am diving into the world of Angular 2 and TypeScript. Despite following along with the video tutorial and using the same code, my implementation is not working as expected, leaving me puzzled. Here is the ...

React error: The DatePickerProps generic type must have one type argument specified

Date Selection Component: import React from "react" import AdapterDateFns from '@mui/lab/AdapterDateFns'; import { LocalizationProvider } from '@mui/lab'; import { DatePicker, DatePickerProps } from '@mui/lab'; cons ...

Issue with Socket.io: Data not received by the last user who connected

I have developed a Node.js and Express application with real-time drawing functionality on canvas using socket.io version 1.7.2. Users are divided into separate socket rooms to enable multiple teams to draw independently. However, there is an issue where t ...

Declaring Typescript modules across multiple .d.ts files

If my original .d.ts definition file is like this: main.d.ts: declare module myMod { } Now, let's say I want to separate out the security definitions into another file but keep them under the same module. Here's what I'm thinking: main. ...

What steps should be taken in order to resolve the error message "Type is missing an index signature"?

Is there a solution to this type error? The argument of type 'Query' is causing an issue as it cannot be assigned to the parameter of type 'Input'. This is due to the absence of an index signature in type 'Query'.(2345) In ...

The React Nested Loop Query: Maximizing Efficiency in Data

Learning React has been a challenge for me, especially when comparing it to XML/XPath. In this scenario, I have two arrays simplified with basic string properties... customerList: Customer[] export class Customer { id: string = ""; firstnam ...

Is it possible to determine the type of a class-type instance using class decorators?

Explore this example of faltering: function DecorateClass<T>(instantiate: (...params:any[]) => T){ return (classTarget:T) => { /*...*/ } } @DecorateClass((json:any) => { //This is just an example, the key is to ensure it returns ...

What is the best way to transform a string into emojis using TypeScript or JavaScript?

Looking to convert emoji from string in typescript to display emoji in html. Here is a snippet of the Typescript file: export class Example { emoji:any; function(){ this.emoji = ":joy:" } } In an HTML file, I would like it to dis ...