Type ' ' cannot be assigned to type ''..ts(2322) ANOTHA ONE

Being a beginner in TypeScript and currently learning about enums, I encountered an error with the following example code that I cannot seem to understand. Here's the code snippet:

enum Status {
    SUCCESS = 'success',
    FAILED = 'failed'
}

interface ResponseSuccess {
    databaseId: number
    sum: number
    from: number
    to: number
}

interface ResponseFail {
    errorMessage: string
    errorCode: number
}

interface GoodResponse {
    status: Status.SUCCESS
    data: ResponseSuccess
}

interface BadResponse {
    status: Status.FAILED
    data: ResponseFail
}

let data: GoodResponse = {
    "status": 'success',  // The error message says: Type '"success"' is not assignable to type 'Status.SUCCESS'.ts(2322)
    "data": {
        "databaseId": 567,
        "sum": 10000,
        "from": 2,
        "to": 4
    }
}

let data2: BadResponse = {
    'status': "failed", // Same error here
    "data": {
        "errorMessage": "Error",
        "errorCode": 4
    }
}

I found a workaround using objects to define my types and it worked perfectly:

const Status = {
    success: 'success',
    failed: 'failed',
} as const

export type StatusType = keyof typeof Status

However, I prefer to have the option to select between "good" and "bad" status types.

Answer №1

The issue arises because 'success' is only a literal String, while IStatus.FAILED is an enum that has the value of success, but its type remains as an enum. For more information, refer to this link.

In this scenario, it is recommended to utilize generics.

interface Response<T extend ResponseSuccess | ResponseFail > {
  status: IStatus;
  data: T
}

let data: Response<ResponseSuccess> = {
  "status": IStatus.SUCCESS, // if 'status' is a literal string, try casting the type: 'success' as IStatus.SUCCESS
  "data": {
    "databaseId": 567,
    "sum": 10000,
    "from": 2,
    "to": 4
  }
}

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

Retrieve all the items listed in the markdown file under specific headings

Below is an example of a markdown file: # Test ## First List * Hello World * Lorem Ipsum * Foo ## Second List - Item 1 ## Third List + Item A Part of Item A + Item B ## Not a List Blah blah blah ## Empty ## Another List Blah blah blah * ITEM # ...

Troubleshooting Next.js and Tailwind CSS Breakpoints: What's causing the

Having trouble with my custom breakpoints. For instance, I attempted the following: <div className="flex flex-row gap-5 mb-5 md:ml-15 sm:ml-15"> ... </div> The margin is not being applied on small and medium screens. Here are the th ...

ts1109: An error occurred as there was an expectation for an angular

I am encountering an error while creating a simple form with Angular using a reactive form. I'm puzzled as to why it's indicating that something is missing: Although I have created forms numerous times before, this is the first instance of such ...

Instance property value driven class property type guard

Is it possible to create a class example that can determine the config type based on the value of animalType instance: enum Animal { BIRD = 'bird', DOG = 'dog', } type Base = { id: number } // Object example type Smth = Base & ...

What is preventing me from using the "@" symbol to substitute the lengthy relative path in my __tests__ directory?

When I initialized my Vue project using vue-cli, I encountered an issue where the use of @ in my src folder was functioning correctly, but not in my __tests__ folder. I have already added configurations to my tsconfig.json file, although I am unsure if i ...

What is the proper way to mention JavaScript packages when including them as parameters in Angular elements within HTML?

I was looking to enhance the command to be more authoritative. <div (click)="lastCall(999)">click me</div> My attempt to utilize Number.MAX_SAFE_INTEGER resulted in an error from my computer stating that it wasn't recognized. As a result ...

What could be causing the primeng dialog to appear blank when conducting Jasmine tests on this Angular TypeScript application?

Having trouble testing a component due to rendering issues? Check out the code snippet below: import {ChangeDetectionStrategy, Component, EventEmitter, Input, Output} from '@angular/core'; @Component({ selector: 'app-help', cha ...

One issue that may arise is when attempting to use ngOnDestroy in Angular components while rearranging user transitions

Encountered an issue recently with Angular - when the user navigates from component A to component B, component A remains active unless ngOnDestroy is triggered. However, if the user visits component B before going to component A and then leaves, ngOnDes ...

How can we dynamically render a component in React using an object?

Hey everyone, I'm facing an issue. I would like to render a list that includes a title and an icon, and I want to do it dynamically using the map method. Here is the object from the backend API (there are more than 2 :D) // icons are Material UI Ic ...

I am experiencing difficulties with TypeORM connecting to my Postgres database

Currently, I am utilizing Express, Postgres, and TypeORM for a small-scale website development project. However, I am encountering challenges when it comes to establishing a connection between TypeORM and my Postgres database. index.ts ( async ()=>{ ...

Signal a return type error when the provided element label does not correspond with an existing entity

I am working on a component that accepts three props: children (React elements), index, and label. The goal is for the component to return the child element at a specific index when index is passed, and to return the element with a specific label when la ...

Is there a way for me to access the data stored in session storage in Next.js?

One of the components in my project is a slider, which allows users to set the number of columns in an Image Gallery component. This code snippet shows the implementation of the slider component: export default function Slider({ value, handleChange }: ISl ...

Testing useEffect with React hooks, Jest, and Enzyme to add and remove event listeners on a ref

Here is a component I've been working on: export const DeviceModule = (props: Props) => { const [isTooltipVisible, changeTooltipVisibility] = useState(false) const deviceRef = useRef(null) useEffect(() => { if (deviceRef && dev ...

How to verify in HTML with Angular whether a variable is undefined

When it comes to the book's ISBN, there are instances where it may not be defined. In those cases, a placeholder image will be loaded. src="http://covers.openlibrary.org/b/isbn/{{book.isbn[0]}}-L.jpg?default=false" ...

Ensuring File Size and Format Compliance in Angular's HTML and TypeScript

I'm currently tackling a file upload feature on an ASP.net webpage using Angular. I have a question: How can I verify if the uploaded file is either a PDF or JPG and does not exceed 2MB in size? If these conditions are not met, I would like to displa ...

Stop receiving updates from an Observable generated by the of method

After I finish creating an observable, I make sure to unsubscribe from it immediately. const data$ = this.httpClient.get('https://jsonplaceholder.typicode.com/todos/1').subscribe(res => { console.log('live', res); data$.unsubscr ...

What could be causing the issue with Vite build and npm serve not functioning together?

After shifting from CRA to VITE, I am encountering a problem with serving my app. I successfully build my app using vite build. and can serve it using Vite serve without any issues. However, I want to use npm's serve command. Whenever I run vite bui ...

Apologies, the module "@org-name/package-name" could not be located

I've hit a roadblock for the past few days. My goal is to create a new npm package that wraps an API I've been developing. When bundling the package, everything seems to be fine in the /dist folder. However, when attempting to test it in a front ...

Angular 2 offers a powerful feature called ngFor that allows developers to

Is there a way to allow users to enter keywords in an input field to filter items within a list of menu items dynamically without using ngModel? I need this to be done without the use of buttons as well. Any suggestions for a workaround? <div class=" ...

Angular 7 and its scrolling div

Currently, I am working on implementing a straightforward drag and drop feature. When dragging an item, my goal is to scroll the containing div by a specified amount in either direction. To achieve this, I am utilizing Angular Material's CDK drag an ...