An example of what I am trying to achieve:
class Test {
private _folderId: number;
private _pageId: number;
private _folderName: string;
private _pageName: string;
constructor(pageId: string | number, folderId: string | number){
this._folderId = (!isNaN(+folderId)) ? folderId : undefined;
this._pageId = (!isNaN(+pageId)) ? pageId : undefined;
this._folderName = (isNaN(+folderId)) ? folderId : undefined;
this._pageName = (isNaN(+pageId)) ? pageId : undefined;
}
}
Unfortunately this throws compiler error:
TS2322:Type 'string | number' is not assignable to type 'number'. Type 'string' is not assignable to type 'number'.
and so on (similar error for each var).
Is there any way around it? At the moment only thing I can do is to set page and folder id to type any...
Use the strict equality operator (===) to check if two strings are equal in TypeScript, e.g. if (str1 === str2) {} . The strict equality operator returns true if the strings are equal, otherwise false is returned. Copied!
'string' is a primitive, but 'String' is a wrapper object. Prefer using 'string' when possible.
Number. As in JavaScript, all numbers in TypeScript are either floating point values or BigIntegers. These floating point numbers get the type number , while BigIntegers get the type bigint .
The comment under the Guenter Guckelsberger's answer suggests you need to use strings like '123'
as numbers. Here is a solution:
/**
* See http://stackoverflow.com/questions/9716468/is-there-any-function-like-isnumeric-in-javascript-to-validate-numbers
*/
function isNumeric(n: any) : n is number | string {
return !isNaN(parseFloat(n)) && isFinite(n);
}
function intVal(n: number | string): number {
return typeof n === "number" ? n : parseInt(n, 10);
}
class Test {
private _folderId: number;
private _pageId: number;
private _folderName: string;
private _pageName: string;
constructor(pageId: string | number, folderId: string | number) {
if (isNumeric(folderId))
this._folderId = intVal(folderId);
else
this._folderName = <string>folderId;
if (isNumeric(pageId))
this._pageId = intVal(pageId);
else
this._pageName = <string>pageId;
}
}
You should use the typeof operator like
typeof folderId === "number"
to check for number or string.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With