类型 "undefined" 不可分配给类型 1 | -1

type "undefined" is not assignable to type 1 | -1

我是打字稿的新手,我正在尝试对我的网站进行排序,我正在尝试使用 functio sortItems

    const sortItems: (a: typeSort, b: typeSort) => () => 1 | -1 = (a, b) => {
        const author1: string = a.author as string;
        const author2: string = b.author as string;
        switch (currentSort) {
            case 'AUTHOR':
                return () => {
                    if (author1 > author2) return 1;
                    if (author1 < author2) return -1;
                };
            default:
                return () => {
                    if (a.name > b.name) return 1;
                    if (a.name < b.name) return -1;
                };
        }
    };

但我总是出错

Type '(a: typeSort, b: typeSort) => () => 1 | -1 | undefined' is not assignable to type '(a: typeSort, b: typeSort) => () => 1 | -1'.
  Call signature return types '() => 1 | -1 | undefined' and '() => 1 | -1' are incompatible.
    Type '1 | -1 | undefined' is not assignable to type '1 | -1'.
      Type 'undefined' is not assignable to type '1 | -1'.ts(2322)

我尝试将 undefined 添加到我的 return 类型,但随后我在 array.sort(sortItems)

中收到错误
Argument of type '(a: typeSort, b: typeSort) => () => 1 | -1' is not assignable to parameter of type '(a: { createdAt: string; _id: string; name: string; description: string; author?: string | undefined; startId?: string | undefined; items?: { _id: string; name: string; description?: string | undefined; }[] | undefined; }, b: { ...; }) => number'.
  Types of parameters 'a' and 'a' are incompatible.
    Type '{ createdAt: string; _id: string; name: string; description: string; author?: string | undefined; startId?: string | undefined; items?: { _id: string; name: string; description?: string | undefined; }[] | undefined; }' is not assignable to type 'typeSort'.
      Types of property 'author' are incompatible.
        Type 'string | undefined' is not assignable to type 'string'.
          Type 'undefined' is not assignable to type 'string'.ts(2345)

我的类型排序类型是:

type typeSort = {
    createdAt: string;
    _id: string;
    name: string;
    description: string;
    author?: string;
    startId?: string | undefined;
    items?: { _id: string; name: string; description?: string | undefined }[] | undefined;
};

如何强制打字稿定义 return 始终为 1 或 -1?我尝试使用类似

的东西
if(a === undefined || b === undefined){
    ...restOfSwitch
}

但它不起作用:(

我假设你的错误是:

return () => {
                if (author1 > author2) return 1;
                if (author1 < author2) return -1;
            };

如果author1 == author2会怎样?你不是 return 1 或 -1,而是 undefined 这是错误的。

可能的解决方案

您可以使用三元运算符简化 return 语句并摆脱不必要的复杂性:

switch (currentSort) {
        case 'AUTHOR':
            return author1 > author2 ? 1 : -1
        default:
            return a.name > b.name ? 1 : -1
    }