gpt4 book ai didi

Typescript - 无法推断参数类型

转载 作者:行者123 更新时间:2023-12-05 05:45:03 27 4
gpt4 key购买 nike

我正在尝试同时为多个数字类型实现 clamp,如下所示:

import BigNumber from 'bignumber.js'

export const clamp = <T extends number | BigNumber>(min: typeof n, n: T, max: typeof n): T => {
if (isNumber(n)) {
return Math.max(min, Math.min(n, max)) as T
}

if (isBigNumber(n)) {
return BigNumber.max(min, BigNumber.min(n, max)) as T
}
}

const isNumber = (n: number | BigNumber): n is number => {
return typeof n === 'number'
}

const isBigNumber = (n: number | BigNumber): n is BigNumber => {
return n instanceof BigNumber
}

但是代码编译失败,出现以下错误:

TypeScript error in clamp.ts(5,21):
Argument of type 'number | BigNumber' is not assignable to parameter of type 'number'.
Type 'BigNumber' is not assignable to type 'number'. TS2345

3 | export const clamp = <T extends number | BigNumber>(min: typeof n, n: T, max: typeof n): T => {
4 | if (isNumber(n)) {
> 5 | return Math.max(min, Math.min(n, max)) as T
| ^
6 | }
7 |
8 | if (isBigNumber(n)) {

minmax 的类型不应该被推断为第 5 行的 number 吗?如果不是,如何保证 Typescript 类型的正确性?

最佳答案

不幸的是,这是 Typescript 类型系统不足的情况之一。有 a proposal允许交集类型守卫,这将使我们能够拥有一个类型守卫,例如:

const isNumber = (n: number | BigNumber, min: typeof n, max: typeof n): n is number & min is number & max is number => {
return typeof n === 'number';
}

在实现这样的提议之前,您必须显式地对 minmax 变量进行类型检查:

import BigNumber from 'bignumber.js'

export const clamp = <T extends number | BigNumber>(min: T, n: T, max: T): number | BigNumber => {
if (isNumber(n) && isNumber(min) && isNumber(max)) {
return Math.max(min, Math.min(n, max));
}

if (isBigNumber(n) && isBigNumber(min) && isBigNumber(max)) {
return BigNumber.min(min, BigNumber.max(n, max));
}

throw new TypeError("Every parameter of this function must be either of type number or an instance of BigNumber");
}

const isNumber = (n: number | BigNumber): n is number => {
return typeof n === 'number'
}

const isBigNumber = (n: number | BigNumber): n is BigNumber => {
return n instanceof BigNumber
}

或者同时转换最小值和最大值:

import BigNumber from 'bignumber.js'

export const clamp = <T extends number | BigNumber>(min: T, n: T, max: T): number | BigNumber => {
if (isNumber(n)) {
return Math.max(min as number, Math.min(n, max as number));
}

return BigNumber.min(min as BigNumber, BigNumber.max(n, max as BigNumber));
}

const isNumber = (n: number | BigNumber): n is number => {
return typeof n === 'number'
}

关于Typescript - 无法推断参数类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71468113/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com