Tom Tom - 2 months ago 18
TypeScript Question

String or Number values in Typescript

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

Answer

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