Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/angular/27.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/sockets/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Typescript 如何正确更改变量';什么是打字脚本?_Typescript_Angular_Typescript1.5 - Fatal编程技术网

Typescript 如何正确更改变量';什么是打字脚本?

Typescript 如何正确更改变量';什么是打字脚本?,typescript,angular,typescript1.5,Typescript,Angular,Typescript1.5,谢谢你的耐心,我刚开始打字 我正在开发angular 2应用程序,它需要接受文本输入,然后进行一系列计算。我(错误地?)假设我需要首先将输入绑定到数据模型中的“任意”类型变量,然后将这些变量转换为数字,以便处理数字。我环顾四周,找不到如何做到这一点,它不会抛出以下TS编译器错误: `src/calculator_service.ts(40,5): error TS2322: Type 'number' is not assignable to type 'string'.` 在我的计算器服务中

谢谢你的耐心,我刚开始打字

我正在开发angular 2应用程序,它需要接受文本输入,然后进行一系列计算。我(错误地?)假设我需要首先将输入绑定到数据模型中的“任意”类型变量,然后将这些变量转换为数字,以便处理数字。我环顾四周,找不到如何做到这一点,它不会抛出以下TS编译器错误:

`src/calculator_service.ts(40,5): error TS2322: Type 'number' is not assignable to type 'string'.`
在我的计算器服务中,我有以下功能:

/*
 * Convert the object of strings recieved from the form into a clean object of integers
 */
n(model:ModelFields) {
    // Clone it
    this.numericModel = Object.assign({}, this.model);

    for (var prop in this.numericModel) {
        if (this.numericModel.hasOwnProperty(prop)) {

            // strip off all non-numeric charactersklj
            this.numericModel[prop] = this.numericModel[prop].replace(/\D/g,'');

            // convert to Any typescript type
            // this breaks the application, and still throws a compiler error. nope.
            // this.numericModel[prop] = this.numericModel[prop]:Any;

            // convert to Number type
            // this gives a typescript console error, but seems to still compile... 
            // ignoring this for now in order to meet deadline
            this.numericModel[prop] = +this.numericModel[prop];

        }
    }

    return this.numericModel;
}
还有ModelFields定义(谢谢tarh!)


有什么想法吗?谢谢大家

您的示例不够清楚,但我猜您的问题是由于类型脚本推断造成的:

var x = 3; // x is a number
x = "45";  // compiler error
但是,如果你这样做:

var x : any = 3; // x can be anything
x = "45";
或:

您可以在和上找到更多详细信息


希望这能有所帮助…

您不能在TypeScript中更改变量的类型,这与TS的用途正好相反。相反,您可以将变量声明为“any”,这相当于JS中的经典“var”变量,未类型化

声明变量后,您将无法重新键入它。但是,您可以做的是声明“any”,然后在您想要使用它时强制转换它,以便将其用作所需的类型

例如,这不会引发任何错误:

let a: any;

a = 1234;
(a as number).toExponential();

a = "abcd"; 
(a as string).substr(1, 4);
对于您的类,这也是正确的,没有类型错误:

class ModelFields { 
    constructor( 
        public fieldName: any, 
        public anotherField: any 
    ) 

    //...
}

let model: ModelFields = new ModelFields(1, 2);

console.log(model.fieldName + model.anotherField);    // --> 3

model.fieldName = "a";
model.anotherField = "b";

console.log(model.fieldName + model.anotherField);    // --> ab

面对类似的问题,为我工作

我的案例:

文章Id
以字符串格式从route params和API中获取数字格式的数据

如果我检查一下!=,ES lint抛出一个错误。因此,我使用number()方法将一个字符串转换为香草javascript中的数字

参考链接:


  • ModelFields
    的定义是什么?@Tarh
    导出类ModelFields{constructor(public fieldName:any,public anotherField:any){}
    @ryanrain已经很久了,但我很好奇,我的帖子回答了你的问题吗?非常感谢Yaniv,很抱歉,我不清楚。我想我理解类型脚本推理的概念-非常重要。在我的代码中,可能是我使用了
    replace
    string方法,使TypeScript知道我的
    model
    是字符串的对象。为了澄清这一点,我想问一下,是否有可能显式正确地更改变量的类型,比如从字符串更改为数字,而不会导致编译器错误。这有意义吗?URL对幻灯片无效。只需添加一个加号:
    +this.route.snapshot.params['articleId']
    let a: any;
    
    a = 1234;
    (a as number).toExponential();
    
    a = "abcd"; 
    (a as string).substr(1, 4);
    
    class ModelFields { 
        constructor( 
            public fieldName: any, 
            public anotherField: any 
        ) 
    
        //...
    }
    
    let model: ModelFields = new ModelFields(1, 2);
    
    console.log(model.fieldName + model.anotherField);    // --> 3
    
    model.fieldName = "a";
    model.anotherField = "b";
    
    console.log(model.fieldName + model.anotherField);    // --> ab
    
    const articleId = Number(this.route.snapshot.params['articleId']);
    
    data.forEach((element, index) => {
    
        // console.log(typeof(element['id']), element['id']); 
        // 4, number
        // console.log(typeof(this.route.snapshot.params['articleId']), this.route.snapshot.params['articleId']);
        // 4, string (converted to number)
    
        if (element['id'] !== articleId) {
            //my implementation
         }
    }