typescript - 如何在 TypeScript 中正确更改变量的类型?

标签 typescript angular typescript1.5

感谢您的耐心等待,我才刚刚开始使用 TypeScript。

我正在开发一个需要接受文本输入然后进行大量计算的 Angular 2 应用程序。我(错误地?)假设我需要首先将输入绑定(bind)到我的数据模型中的“任何”类型变量,然后将这些变量转换为数字以处理数字。我环顾四周,找不到如何以不引发此 TS 编译器错误的方式执行此操作:

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

在我的 CalculatorService 中,我有这个功能:

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

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

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

最佳答案

您不能在 TypeScript 中更改变量的类型,这恰恰与 TS 的目的相反。相反,您可以将变量声明为“any”,这相当于 JS 中的经典“var”变量,无类型。

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

例如这不会抛出任何错误:

let a: any;

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

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

对于您的类(class),这也是正确的,没有类型错误:

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 - 如何在 TypeScript 中正确更改变量的类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33615680/

相关文章:

intellij-idea - AngularJS 2.0 TypeScript Intellij 想法(或 webstorm) - ES6 导入语法

node.js - 在 typescript 中读取和写入文本文件

Typescript - 获取接口(interface)的所有实现

arrays - TypeScript - 数组 toString()

angular - 无法在 Angular 5 中使用 HttpClient

javascript - 使用 angular2 将 HTML 从服务器插入 DOM(Angular2 中的一般 DOM 操作)

javascript - Angular2 - 在不同文件中拆分应用程序时出现引用错误

javascript - 无法将 sourceMap(.map) 文件移动到 Typescript 中的单独文件夹

node.js - Visual Studio Code - 通过 TypeScript 调试 Node JS

ubuntu - 如何与 Flask 后端 api 一起构建 Angular 2 前端应用程序?