typescript TS在从接口扩展的泛型类型上抛出错误

bjg7j2ky  于 2023-08-07  发布在  TypeScript
关注(0)|答案(1)|浏览(105)

我有三个接口:
A.ts

export interface A {
    requestID: number;
    createdUser: string;
    createdDate: string;
    text: string
}

字符串

B.ts

export interface B {
    requestID: number;
    createdUser: string;
    createdDate: string;
    department: string;
    emailID: string;
}

AB.ts

export interface AB extends A, B {
    requestType: string;
    assignedUser: string;
}


现在,我在泛型方法中使用这些接口来执行一些排序功能:

function sort<T extends AB | A | B>(requests: T[], columnName: string) {
    switch columnName {
        case "requestID": {
            requests.sort((a, b) => a.requestID > b.requestID ? 1 : -1);
        } case "requestType": {
            requests.sort((a, b) => a.requestType > b.requestType ? 1 : -1);
            break;
        } case "text": {
            requests.sort((a, b) => a.text > b.text ? 1 : -1);
            break;
        } case "department": {
            requests.sort((a, b) => a.department > b.department ? 1 : -1);
            break;
        }
    }
}


但是,我得到了下面的错误:

Property 'requestType' does not exist on type 'AB | A | B'.


由于requests的类型是T,这是一个泛型(它是从ABAB扩展而来的),我相信它应该有requestType属性,它不应该抛出这个错误。我哪里错了吗?

f45qwnt8

f45qwnt81#

您的情况非常简单,不需要以不同的方式处理不同的列
只需要使用一个完全通用的排序器:

function sort<T, K extends keyof T>(list: T[], prop: K) {
    return list.sort((a, b) => a[prop] > b[prop] ? 1 : -1);
}

字符串
或者在你的自定义排序器中调用它(添加了K extends keyof T)来排序

相关问题