如何在TypeScript中正确更改变量的类型? [英] How to properly change a variable's type in TypeScript?

查看:1434
本文介绍了如何在TypeScript中正确更改变量的类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

感谢您的耐心等待,我只是从TypeScript开始.

Thanks for your patience here, I'm just starting out with TypeScript.

我正在开发一个angular 2应用程序,该应用程序需要接受文本输入,然后进行大量计算.我(不正确吗?)假设我需要先将输入绑定到数据模型中的"any"类型变量,然后将这些变量转换为数字以便处理数字.我四处张望,找不到如何不会引发此TS编译器错误的方法:

I'm working on an angular 2 app that needs to accept text inputs and then make a bunch of calculations. I (incorrectly?) assumed that i would need to first bind inputs to "any" type variables within my data model and then convert those variables to numbers in order to crunch numbers. I've looked all around, and can't find how to do this in such a way that it doesn't throw this TS compiler error:

`src/calculator_service.ts(40,5): error TS2322: Type 'number' is not assignable to type 'string'.`

在我的CalculatorService中,我具有以下功能:

Within my CalculatorService, I have this function:

/*
 * 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!)

and the ModelFields definition (thanks tarh!)

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

有什么想法吗?谢谢大家!

Any ideas? Thanks everybody!

推荐答案

您无法在TypeScript中更改变量的类型,这与TS恰好相反.相反,您可以将变量声明为"any",这等同于JS中经典的无类型变量"var".

You cannot change a variable's type in TypeScript, that's just the opposite TS was made for. Instead, you can declare a variable as "any", which would be equivalent to a classic "var" variable in JS, untyped.

一旦声明了变量,您将无法重新键入它.但是,您可以做的是先声明"any",然后在需要使用它时将其强制转换,以将其用作所需的类型.

Once a variable is declared, you will not be able to retype it. What you could do, however, is to declare "any" and then cast it whenever you want to use it, in order to use it as the desired type.

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

For example this would not throw any errors:

let a: any;

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

a = "abcd"; 
(a as string).substr(1, 4);

对于您的班级来说,这也是正确的,没有类型错误:

In case of your class, this would be also correct, no type errors:

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

这篇关于如何在TypeScript中正确更改变量的类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆