TypeScript类型检测不通过,我在写一个选择排序可以传入number,string, 和自定义的Comparable?
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"]);
回答
把自己绕进去了吧
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"]));
而且你这啥排序算法
以上是 TypeScript类型检测不通过,我在写一个选择排序可以传入number,string, 和自定义的Comparable? 的全部内容, 来源链接: utcz.com/a/41601.html