I have a class BigNumber whose constructor takes an initialising argument that can be either a string, number or a BigNumber. The constructor will initialise an instance of BigNumber using the appropriate strategy given the type of the argument:
export class BigNumber
{
private static isDecimal = /^(\d+(\.\d*)?|\.\d+)(e[+-]?\d+)?$/i;
public d : number[];
public e : number;
public s : number;
constructor(v : string | number | BigNumber)
{
let e, i, t,
x = this;
if (v instanceof BigNumber)
{
// code dependent of v being a BigNumber
x.s = v.s;
x.e = v.e;
x.d = v.d.slice();
return;
}
else if (typeof v === 'number')
{
// code dependent of v being a number
if (v === 0)
{
x.s = (1 / v < 0) ? -1 : 1;
x.e = 0;
x.d = [0];
return;
}
// Other stuff
}
else if(typeof v === 'string')
{
// code dependent of v being a string
if (v.charCodeAt(0) === 45)
{
v = v.slice(1);
x.s = -1;
}
else
{
x.s = 1;
}
// Other stuff
}
else
{
// throw error
}
}
}
The problem is typescript kicks up a lot of errors relating to making assignments or calling functions like slice() in the string section i.e. typeguards are not working.
These can be fixed with explicit casts on each operation however I was under the impression that the typescript compiler was able to infer the type within a instanceOf or typeof block. Where have I gone wrong?
console.log(v.slice(0, 3))when it's a string I get no errors. Please provide the code that results in errors for you. - Nitzan Tomer