Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to properly change a variable's type in TypeScript?

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

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'.`

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;
}

and the ModelFields definition (thanks tarh!)

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

Any ideas? Thanks everybody!

like image 309
ryanrain Avatar asked Nov 09 '15 18:11

ryanrain


People also ask

How do I change a variable type in TypeScript?

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. Once a variable is declared, you will not be able to retype it.

What does ?: Mean in TypeScript?

What does ?: mean in TypeScript? Using a question mark followed by a colon ( ?: ) means a property is optional. That said, a property can either have a value based on the type defined or its value can be undefined .

When to use let and VAR in TypeScript?

The let statement is used to declare a local variable in TypeScript. It is similar to the var keyword, but it has some restriction in scoping in comparison of the var keyword. The let keyword can enhance our code readability and decreases the chance of programming error.

How do you declare a variable with two types TypeScript?

In TypeScript, a union type variable is a variable which can store multiple type of values (i.e. number, string etc). A union type allows us to define a variable with multiple types. The union type variables are defined using the pipe ( '|' ) symbol between the types. The union types help in some special situations.


2 Answers

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.

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
like image 74
josemigallas Avatar answered Oct 15 '22 22:10

josemigallas


You example is not clear enough, but I guess that your problem is because of Typescript inference:

var x = 3; // x is a number
x = "45";  // compiler error

But, if you do:

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

Or:

var x; // x is any forever
x = '45';  // x is still any

You can find further details on those great slides and on docs

Hope this can help a bit...

like image 29
Yaniv Efraim Avatar answered Oct 15 '22 21:10

Yaniv Efraim