typescript Angular2 错误:类型“数字”不可分配给类型“数字构造函数”

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/40944150/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 04:03:15  来源:igfitidea点击:

Angular2 Error: Type 'number' is not assignable to type 'NumberConstructor'

javascriptangulartypescript

提问by anonym

In the following Angular2 program where I want the system to randomly choose four choices from either 0 or 1. I'm getting the desired output and the console doesn't report any error. However, my IDE displays the following error:

在下面的 Angular2 程序中,我希望系统从 0 或 1 中随机选择四个选项。我得到了所需的输出并且控制台没有报告任何错误。但是,我的 IDE 显示以下错误:

Angular2 Error

Angular2 错误

I tried changing Numberto numberbut it yields another error:

我尝试更改Number为,number但它产生了另一个错误:

Another Error

另一个错误

Component Code

组件代码

import {Component} from 'angular2/core';
import {OnInit} from 'angular2/core';

@Component(
{
    selector: 'puzzle',
    template: `
        <section class="combination">
            I:   {{ switch1Number }}<br>
            II:  {{ switch2Number }}<br>
            III: {{ switch3Number }}<br>
            IV:  {{ switch4Number }}
        </section>
    `
})

export class PuzzleComponent implements OnInit {
    switch1Number = Number;
    switch2Number = Number;
    switch3Number = Number;
    switch4Number = Number;

    ngOnInit() {
        // Math.randon gives a random decimal value between 0 & 1.
        // Math..round rounds it to 0 or 1
        this.switch1Number = Math.round(Math.random());
        this.switch2Number = Math.round(Math.random());
        this.switch3Number = Math.round(Math.random());
        this.switch4Number = Math.round(Math.random());

        console.log(this.switch1Number, this.switch2Number, this.switch3Number, this.switch4Number);
    }
}

采纳答案by Ankit Singh

Replace Numberwith numberin

更换Numbernumber

switch1Number = Number

it should be

它应该是

switch1Number: number;

Numberis not a type of variable, it's a number constructorjust likeStringis a stringtype constructor.

Number不是一种类型的变量,它是一个数字constructor,就像String是一种string类型constructor