TypeScript类型检测不通过,我在写一个选择排序可以传入number,string, 和自定义的Comparable?

jsdeferred
  • 2.6k

codesandbox链接

interface Comparable<T> {
  compareTo(that: T): number;
  equals(that: T): boolean;
}

function selectionSort<E extends Comparable<E> | number | string>(
  arr: E[]
): E[] {
  if (!arr.length) return arr;
  if (typeof arr[0] === "number" || typeof arr[0] === "string") {
    for (let i = 0; i < arr.length; i++) {
      let minIndex = 0;
      for (let j = i; j < arr.length; j++) {
        if (arr[j] < arr[minIndex]) {
          minIndex = j;
        }
      }

      const temp = arr[i];
      arr[i] = arr[minIndex];
      arr[minIndex] = temp;
    }
  } else {
    arr = arr as Comparable<any>[]
    for (let i = 0; i < arr.length; i++) {
      let minIndex = 0;
      for (let j = i; j < arr.length; j++) {
        if (arr[j].compareTo(arr[minIndex]) < 0) {
          minIndex = j;
        }
      }

      const temp = arr[i];
      arr[i] = arr[minIndex];
      arr[minIndex] = temp;
    }
  }
  return arr;
}

class Student implements Comparable<Student> {
  constructor(private score: number) {}
  compareTo(that: Student): number {
    return this.score - that.score;
  }
  equals(that: Student): boolean {
    return this.score === that.score;
  }
}

selectionSort<Student>([new Student(1)]);
selectionSort<number>([1, 2, 3]);
selectionSort<string>(["1", "2", "3"]);
回复
阅读 547
2 个回答

把自己绕进去了吧

type Comparable = {
  compareTo(that: Comparable): number;
  equals(that: Comparable): boolean;
};

type SortItem = number | string | Comparable;

function isComparableList(arr: SortItem[]): arr is Comparable[] {
  const type = typeof arr[0];
  return type !== "number" && type !== "string";
}

function selectionSort<T extends SortItem>(arr: T[]): T[] {
  if (isComparableList(arr)) {
    for (let i = 0; i < arr.length; i++) {
      let minIndex = 0;
      for (let j = i; j < arr.length; j++) {
        if (arr[j].compareTo(arr[minIndex]) < 0) {
          minIndex = j;
        }
      }
      const temp = arr[i];
      arr[i] = arr[minIndex];
      arr[minIndex] = temp;
    }
  } else {
    for (let i = 0; i < arr.length; i++) {
      let minIndex = 0;
      for (let j = i; j < arr.length; j++) {
        if (arr[j] < arr[minIndex]) {
          minIndex = j;
        }
      }
      const temp = arr[i];
      arr[i] = arr[minIndex];
      arr[minIndex] = temp;
    }
  }
  return arr;
}

class Student implements Comparable {
  constructor(private score: number) {}
  compareTo(that: Student): number {
    return this.score - that.score;
  }
  equals(that: Student): boolean {
    return this.score === that.score;
  }
}

console.log(selectionSort([new Student(1)]));
console.log(selectionSort([1, 2, 3]));
console.log(selectionSort(["1", "2", "3"]));

而且你这啥排序算法

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
你知道吗?

宣传栏