这样写是可以的, ts 不报错:
interface GetNumber {
name: "GetNumber";
}
interface GetString {
name: "GetString";
}
function get(options: GetNumber): number
function get(options: GetString): string
function get(options: GetNumber | GetString) {
switch (options.name) {
case "GetNumber":
return 1 + 1
case "GetString":
return `${1 + 1}`
default:
throw new Error("param error")
}
}
下面这样不行, ts 报错: Type 'string | number' is not assignable to type 'number'.
// 可是我的 FuncGet 类型 是从另一个文件里引入的
// 做不到像上面那么写
// 那么我该怎么写呢?
interface FuncGet {
(options: GetNumber): number;
(options: GetString): string;
}
// ts 编译错误: Type 'string | number' is not assignable to type 'number
const get: FuncGet = (options: GetNumber | GetString) => {
switch (options.name) {
case "GetNumber":
return 1 + 1
case "GetString":
return `${1 + 1}`
default:
throw new Error("param error")
}
}