在普通的无类型 Javascript 中,编写一个可以对数字或 bigint 进行操作的函数并不难,具体取决于传入的参数:
const sumOfSquares = (a,b) => a*a + b*b;
sumOfSquares(3, 4); // returns 25
sumOfSquares(3n, 4n); // returns 25n
sumOfSquares(3n, 4); // throws a TypeError
似乎应该有一种方法可以在 typescript 中声明这个函数,以便编译器强制参数一起工作。我试过了const sumOfSquares = <N extends bigint | number>(a: N, b: N): N =>
a * a + b * b;
但是编译器拒绝了这一点:semantic error TS2322: Type 'number' is not assignable to type 'N'.
'number' is assignable to the constraint of type 'N', but 'N' could be instantiated with a different subtype of constraint 'number | bigint'.
是否有不同的方法来编写类型声明以便它可以工作?
最佳答案
重载有用吗?
function isBigInt(a: bigint | number): a is bigint {
return typeof (a) === 'bigint'
}
function isNumber(a: bigint | number): a is number {
return typeof (a) === 'number'
}
function doSomething(a: bigint, b: bigint): bigint;
function doSomething(a: number, b: number): number;
function doSomething(a: bigint | number, b: bigint | number): bigint | number | never {
if (isBigInt(a) && isBigInt(b))
return a + b;
else if (isNumber(a) && isNumber(b))
return a + b;
throw 'error';
}
let a = doSomething(1, 1)
let b = doSomething(1n, 1n)
let c = doSomething(1n, 1)
关于javascript - 是否可以声明一个适用于数字和大整数的 typescript 函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65280785/