type t = string | number
const test = (a: t, b: t) : t => {
return a + b
}
我的本意是当test函数调用时,a和b的类型必须一样,即都为string或者都为number,但是这样写似乎不生效,应该如何实现呢
###用重载。
###const test = <T extends (string | number)>(a: T, b: T) => {
return a + b;
};
###// const test = <T extends string | number>(x: T, y: T): T {
// return (x as any) + (y as any);
// }
// test("a", "b"); // OK
// test(5, 3); // OK
// test(1,"2"); // error
function test<T extends string | number>(x: T, y: T): T;
function test(x: any, y: any) {
return x + y;
}
let s = test("a", "b"); // fine
let n = test(1, 2); // fine
let n2 = test(1,"2"); // error
###const test = <T extends (string | number)>(a: T, b: T): T => {
return <any>a + <any>b;
};