Joe
Joe

Reputation: 834

variable assignment from "any" returns incorrect data type

i am serializing/mapping data from httpclient's result as shown below:

export class Foo {
    constructor() {
        this.bar = 0.00;
    }
    bar: number;
}

fromJson(json: any) : Foo {
    const foo = new Foo();
    foo.bar = json.bar;
    return foo;
}

when i write console.log(typeof foo.bar), i get string rather than number. is this the intended result and i really need to type cast foo.bar = parseInt(json.bar)?

Upvotes: 1

Views: 43

Answers (2)

abarrenechea
abarrenechea

Reputation: 184

Can't comment yet, but wanted to share a codepen with a little proof of concept: https://codepen.io/abarrenechea/pen/xQOqdX

class Foo {
  constructor() {
    this.bar = 0.00;
  }
  bar: number;
}

var foo1 = new Foo();
foo1.bar = "Hello";

var foo2 = new Foo();
foo2.bar = 10;

var foo3 = new Foo();
foo3.bar = true;

document.getElementById("foo1").innerHTML = foo1.bar + " | Type: " + typeof foo1.bar; // this is a string
document.getElementById("foo2").innerHTML = foo2.bar + " | Type: " + typeof foo2.bar; // this is a number
document.getElementById("foo3").innerHTML = foo3.bar + " | Type: " + typeof foo3.bar; // this is a boolean

Variables are overriden if you need to maintain the type you should cast first.

Upvotes: 0

T.J. Crowder
T.J. Crowder

Reputation: 1074435

when i write console.log(typeof foo.bar), i get string rather than number. is this the intended result

Yes. TypeScript doesn't insert conversion code for you.

...and i really need to type cast foo.bar = parseInt(json.bar)?

That's not a cast¹, but yes, you do need to convert to number if your starting point is not a number (and parseInt is one way to do that — there are several, each with pros and cons — if your starting point is a string).

¹ And in fact, TypeScript doesn't have casts, it has type assertions, which are similar but different.

Upvotes: 3

Related Questions