typescript 中的字符串或数字值

vshtjzan  于 2022-12-24  发布在  TypeScript
关注(0)|答案(4)|浏览(186)

我正在努力实现的一个例子:

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

不幸的是,这会引发编译器错误:

TS2322:Type 'string | number' is not assignable to type 'number'. Type 'string' is not assignable to type 'number'.

等等(每个VAR的误差相似)。
有什么办法绕过它吗?目前我唯一能做的就是设置页面和文件夹id来键入任何...

vqlkdk9b

vqlkdk9b1#

Guenter Guckelsberger的答案下面的注解建议您需要使用像'123'这样的字符串作为数字。

/**
* 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;
    }
}
gc0ot86w

gc0ot86w2#

您应该使用typeof运算符,

typeof folderId === "number"

以检查数字或字符串。

iqxoj9l9

iqxoj9l93#

因为你提到了pageIdfolderId的一个不明确的类型,所以在赋值的时候,typescript不能分辨你的变量是一个数字还是一个字符串,因此你需要在赋值的时候指定你的变量的确切类型,这可以通过类型转换来完成
您可以将folderIdpageId类型转换为数字或字符串,如下所示:

constructor(pageId: string | number, folderId: string | number){
    this._folderId = (!isNaN(+folderId)) ? folderId as number : undefined;
    this._pageId = (!isNaN(+pageId)) ? pageId as number : undefined;
    this._folderName = (isNaN(+folderId)) ? folderId as string : undefined;
    this._pageName = (isNaN(+pageId)) ? pageId as string: undefined;
}

类型转换的另一种方法是<number>folderId``<string>folderId,也可以使用type Guards,如“Paleo的答案”中所示

uujelgoq

uujelgoq4#

对于像我这样的人来说,他们来这里寻找一种方法来约束一个类型为字符串,而字符串可以计算为数字,你可以使用模板文本类型。

type SoN = `${number}`
const pass1 = '1'
const pass2 = '-1'
const pass3 = '1.0'
const pass4 = '3e44'
const fail1 = 'abc'
const fail2 = 'NaN'

function sumStrings(str1: SoN, str2: SoN, str3: SoN, str4: SoN, str5: SoN, str6: SoN) {
    return str1 + str2 + str3 + str4 + str5 + str6 // LOL
}

sumStrings(
    pass1,
    pass2,
    pass3,
    pass4,
    fail1,
    fail2
)

在Typescript github问题中对此有一些讨论:

相关问题