I have a Typescript class like this:
export class Contract {
constructor (
public id: string,
public name: string,
public spend: number
) {}
}
This is loaded by a service using an intermediate class like this:
export class ContractService {
// the stuff you would expect
public loadContracts() {
this.httpService.get(this.contractEndpoint).subscribe((result) => this.createContracts(result));
}
private createContracts(contracts: Array<Contract>) {
for ( let contract of contracts ) {
console.log("Contract spend is "+contract.spend+": "+( typeof contract.spend));
}
}
}
When I run it, in my console I see this:
Contract spend is 10000: string
Contract spend is 1222: string
Contract spend is 20001: string
However if I try to use parseInt(contract.spend) then the Typescript compiler refuses because it knows contract.spend to be a number, so at compilation it is aware what the value should be.
I assume that what is happening is that the JSON from my rest service is returning the spend field as a quoted value, but it seems to be subverting one of the core advantages of Typescript in a way that fails silently. What do I need to do to ensure that either my numeric field contains a number or my code fails when the wrong type is handed to it?
"with quotes) or as integer? There is no conversion inside TypeScriptlet stringToNumber: number = +contract.spend.Number(contract.spend)but I was interested in why it failed and yet didn't acknowledge that there was a problem.