简体   繁体   English

Typescript 箭头函数重载错误 2322

[英]Typescript arrow functions overloads error 2322

This code below is working fine, but it gives an error for the resolve constant.下面的代码工作正常,但它给出了resolve常量的错误。

const resolve: Resolve
Type '(param: "case 1" | "case 2" | "case 3") => boolean | "string" | 1000' is not assignable to type 'Resolve'.(2322)
// Overloads
type Resolve = {
    (): false;
    (param: 'case 1'): string;
    (param: 'case 2'): number;
    (param: 'case 3'): true;
};

const resolve: Resolve = (param) => {
    switch (param) {
        case 'case 1':
            return 'string';
        case 'case 2':
            return 1000;
        case 'case 3':
            return true;
        default:
            return false;
    }
};

const result = {
    first: resolve('case 1'),
    second: resolve('case 2'),
    third: resolve('case 3'),
    none: resolve()
};

Any idea how to resolve it?知道如何解决吗?

It's often the case that an overloaded function's implementation signature isn't fully compatible with the overload signatures.通常情况下,重载函数的实现签名与重载签名不完全兼容。 When you're using overload syntax, TypeScript uses relaxed rules for compatibility.当您使用重载语法时,TypeScript 使用宽松的兼容性规则。

In your case, since you're not using overload syntax, you'll have to use a type assertion (after making sure that the function behaves correctly for the overloads):在您的情况下,由于您没有使用重载语法,因此您必须使用类型断言(在确保function 对重载的行为正确之后):

const resolve = ((param?: "case 1" | "case 2" | "case 3"): string | number | true | false => {
    switch (param) {
        case "case 1":
            return "string";
        case "case 2":
            return 1000;
        case "case 3":
            return true;
        default:
            return false;
    }
}) as Resolve;

(I've also added a type annotation to param and a return type annotation, just for good measure, though it's not uncommon to be really loose in the implementation signature.) (我还为param添加了一个类型注释和一个返回类型注释,只是为了更好的衡量,尽管在实现签名中真正松散的情况并不少见。)

Playground example 游乐场示例


Just FWIW, using function overload syntax instead ( playground link ):只是 FWIW,改用 function 重载语法( 游乐场链接):

function resolve(param: "case 1"): string;
function resolve(param: "case 2"): number;
function resolve(param: "case 3"): true;
function resolve(): false;
function resolve(param?: "case 1" | "case 2" | "case 3"): string | number | true | false {
    switch (param) {
        case "case 1":
            return "string";
        case "case 2":
            return 1000;
        case "case 3":
            return true;
        default:
            return false;
    }
};

type Resolve = typeof resolve;

...but that's not always possible, it's not uncommon to have to define the type without ever actually implementing it (for instance, in a callback type for an API). ...但这并不总是可能的,在没有实际实现它的情况下必须定义类型的情况并不少见(例如,在 API 的回调类型中)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM