【问题标题】:How to assign one strict datatype variable value using another variable in angular?如何使用角度中的另一个变量分配一个结构数据类型变量值?
【发布时间】:2020-12-03 17:56:07
【问题描述】:

我是一名 Angular 开发人员,正在从事一个项目,在该项目中我使用严格的 DataType 并使用我的自定义 DataType 定义变量,如下所示:

Code: 1 | 2 | 3 | 4 | 5 = 1;

如果我们直接为这个code 变量分配常量值,那么上面的变量声明将完美地工作。像这样:

Code = 3;

但是如果我尝试使用这样的变量来分配它,这会给出错误:

let num = this.getNumberBewteen1_5();
Code = num;

而函数getNumberBewteen1_5()是返回1到5之间的一个数字的函数;

有什么方法可以在不删除严格的DataType 角度的情况下修复它?

【问题讨论】:

    标签: angular types declare


    【解决方案1】:

    问题是方法返回的类型应该与变量类型相同。
    您尝试将数字分配给 1 | 2 | 3 | 4 | 5 是不同的类型。

    工作示例:

    import { Component } from '@angular/core';
    
    type YourType = 1 | 2 | 3;
    
    @Component({
      selector: 'app-root',
      templateUrl: './app.component.html',
      styleUrls: ['./app.component.css']
    })
    export class AppComponent {
      a: YourType;
    
      constructor() {
        let b = this.yourMethod();
        this.a = b;
      }
    
      yourMethod(): YourType { // returned type is YourType (not number)
        return 1; // or 2 | 3
      }
    }
    

    【讨论】:

    • 感谢帮助我的朋友,感谢您的回答。还有一件事,假设我对数字执行操作以从函数返回值,那么它会起作用吗?
    • 假设,在yourMethod() 函数中,如果我这样执行:if(number > 5) { return 1} else { return number++; } 这个函数会起作用吗?好像这样不行……
    • 如果你这样做return number++ as YourType;就可以了
    猜你喜欢
    • 1970-01-01
    • 2018-03-29
    • 1970-01-01
    • 2013-11-21
    • 2021-04-04
    • 2018-03-17
    • 1970-01-01
    • 1970-01-01
    • 2022-06-11
    相关资源
    最近更新 更多