【问题标题】:Type 'number' is not assignable to type 'UserId'类型 'number' 不可分配给类型 'UserId'
【发布时间】:2021-11-28 20:59:51
【问题描述】:

这是我的课程代码,我收到以下错误: (1)。 Type 'number' is not assignable to type 'UserId'. - 无法理解这个问题。请需要澄清。

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;
  }
}

就我而言,(2) 我需要将id 传递给班级。处理这个问题的最佳做法是什么?

LIVE DEMO

【问题讨论】:

标签: angular typescript typescript-typings typescript-generics


【解决方案1】:

this.id 指向一个类型UserId。但是您想将值传递给idinside UserId。

this.id.id = id -> 试试这个。

【讨论】:

    【解决方案2】:

    这里你期望T 是数字或字符串

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

    但在您的示例中,您传递的接口不符合条件。

    implements Identical<UserId>
    

    传入Identical 只需number 或string 类型

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

    【讨论】:

      【解决方案3】:

      首先,您可以将 id 变量声明为如下所示的数字。

      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 {
        public id: UserId = { id: 5 };
        title = "CodeSandbox";
        constructor() {
          this.id.id = 7;
          // This may fix your issue.
          // Bcs you have declared the `UserId` interface as Object.
        }
      }
      

      为了将id值传递给组件,可以使用输入值。

      Live demo 用于解决上述问题。

      【讨论】:

      • 你的接口根本没有实现
      • 我已经更新了我的解决方案,请检查。
      猜你喜欢
      • 2020-08-07
      • 1970-01-01
      • 1970-01-01
      • 2023-01-22
      • 2017-01-05
      • 2021-01-20
      • 2022-01-16
      • 2021-12-05
      • 2021-09-18
      相关资源
      最近更新 更多