Home > Software engineering >  Type 'number' is not assignable to type 'UserId'
Type 'number' is not assignable to type 'UserId'

Time:10-09

Here is my class code, where I am getting the error as : (1). Type 'number' is not assignable to type 'UserId'. - do not able to understand the issue. please needs the clarification.

component.ts:

import { Component } from "@angular/core";

interface Identical<T extends number | string> {
  id: T;
}

interface UserId {
  id: number;
}

@Component({
  selector: "app-root",
  templateUrl: "./app.component.html",
  styleUrls: ["./app.component.css"]
})
export class AppComponent implements Identical<UserId> {
  id: UserId;
  title = "CodeSandbox";
  constructor(id: number) {
    this.id = id;
  }
}

in my case, (2) I require to pass the id to the class. what is the best practice to handle that?

LIVE DEMO

CodePudding user response:

this.id is pointing to a type UserId. But you want to pass the value to idinside UserId.

this.id.id = id -> Try this.

CodePudding user response:

First, you can declare the id variable to number as below.

import { Component } from "@angular/core";

interface Identical<T extends number | string> {
  id: T;
}

interface UserId {
  id: number;
}

@Component({
  selector: "app-root",
  templateUrl: "./app.component.html",
  styleUrls: ["./app.component.css"]
})
export class AppComponent {
  id: number;
  title = "CodeSandbox";
  constructor(id: number) {
    this.id = id;
  }
}

In order to pass the id value to the component, you can use input value.

Live demo for fixing the above issue.

  • Related