javascript - 是否可以声明一个适用于数字和大整数的 typescript 函数?

标签 javascript typescript types bigint

在普通的无类型 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/

相关文章:

javascript - 无法使用 PHP 和 JQuery Ajax 将新记录插入到 mysql 数据库

javascript - 如何查看 "overflow: auto;"何时从 "scroll"变为 "none"- 简单解决方案

javascript - 多次调用列表格式化程序

typescript - 如何在 typescript 中描述 any|undefined?

python - Python 中类型和对象的先有鸡还是先有蛋悖论

c# - 什么时候类型不是类型?错误 : 'is a type, which is not valid in the given context'

javascript - this.refs.something.value 在 react 中返回未定义

javascript - jQuery 获取子级的精确父级(使用 UL 和 LI)

javascript - 如何将 zingchart 实现到 angular2

Go errors : Is() and As() claim to be recursive, 是否有实现错误接口(interface)并支持此递归的任何类型 - 无错误?