string, b: …

You could use a type template. Something like:

and use your function as:

type Sum = {
    (a: string, b: string): string
    (a: number, b: number): number
}

let sum: Sum = function(
    a: number|string,
    b: number|string
): number|string {
    if (typeof a == "number" && typeof b == "number") {
        return a + b;
    }
    if (typeof a == "string" && typeof b == "string") {
        return a + b;
    }
    throw new Error("error: something");
}

This will throw a type error if you mix

Type '(a: string | number, b: string | number) => string | number' is not assignable to type 'Sum'.
  Type 'string | number' is not assignable to type 'string'.
    Type 'number' is not assignable to type 'string'.(2322)

and

function sum2(a: number, b: number): number;
function sum2(a: string, b: string): string;
function sum2(a: number|string, b: number|string): number|string {
    if (typeof a == "number" && typeof b == "number") {
        return a + b;
    }
    if (typeof a == "string" && typeof b == "string") {
        return a + b;
    }
    throw new Error("error: something");
}

. For example:

解决方案:

type Sum<T> = (a: T, b: T) => T;

so you can declare it like this:

let sum: Sum<string> = function(a: string, b: string): string {...}

let sum: Sum<number> = function(a: number, b: number): number {...}

The type you’ve declared is expecting either a string or number,

//throw type error
let sum: Sum<number> = function(a: number, b: string): number {...} 

but not

给TA打赏
共{{data.count}}人
人已打赏
未分类

将多个列的聚合值作为键,将列转为行。

2022-9-8 16:08:23

未分类

如何使用pandas比较一个数据框的1个元素和其他数据框的所有元素?

2022-9-8 16:08:25

0 条回复 A文章作者 M管理员
    暂无讨论,说说你的看法吧
个人中心
购物车
优惠劵
今日签到
有新私信 私信列表
搜索