Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 835
Tomas Avatar asked Sep 13 '16 10:09

Tomas


People also ask

How do I compare strings and numbers in TypeScript?

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!

Should I use string or string in TypeScript?

'string' is a primitive, but 'String' is a wrapper object. Prefer using 'string' when possible.

What type of value is number in TypeScript?

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 .


2 Answers

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;
    }
}
like image 154
Paleo Avatar answered Oct 09 '22 23:10

Paleo


You should use the typeof operator like

typeof folderId === "number"

to check for number or string.

like image 38
Guenter Guckelsberger Avatar answered Oct 09 '22 23:10

Guenter Guckelsberger