联合类型导致"type lacks a call signature"错误



我想通过使用联合类型在 Typescript 中调用具有两种不同类型的数组的数组排序函数。函数调用适用于单独的类型,但不适用于联合类型?

    this.shuffle(stringArray);  // array of strings
    this.shuffle(StudentArray); // array of student objects
    // this works
    shuffle(arr:Student[]) {
        arr.sort(() => (Math.random() - 0.5))
    }
    // this works
    shuffle(arr:string[]) {
        arr.sort(() => (Math.random() - 0.5))
    }
    // this gives an error
    shuffle(arr:Student[] | string[]) {
        arr.sort(() => (Math.random() - 0.5))
    }

错误

Cannot invoke an expression whose type lacks a call signature.

arr:Student[] | string[]更改为(Student | string)[]

相关内容

最新更新