【问题标题】:How to write a generic interface with mandatory properties, and any possible property from T?如何编写具有强制属性的通用接口以及 T 中的任何可能属性?
【发布时间】:2021-02-13 23:09:52
【问题描述】:

假设我有一个这样的接口/类型:

export interface I_Employee {  
    id:string|number
    availableShifts: Array<string|number > | null;
    unAvailableShifts: Array<string|number > | null
    desiredNumShifts?: number | null
    minNumShifts?: number | null
    maxNumShifts?: number | null
}

但是,我希望实现员工对象具有类型“T”中存在的任何其他属性。看起来像这样:

export interface I_Employee<T> {
    [any key in T...]:T[some key...]//This is just "pseudo code".
    id:string|number
    availableShifts: Array<string|number > | null;
    unAvailableShifts: Array<string|number > | null
    desiredNumShifts?: number | null
    minNumShifts?: number | null
    maxNumShifts?: number | null
}

当然,我可以只做 [index:string]:any,而不是泛型,但是 Typescript 在我的代码的某些部分无法识别属性。我有接收某些对象并变异它们的函数,因此我需要能够以某种方式使其具有通用性。

这个可以吗?

【问题讨论】:

    标签: typescript generics


    【解决方案1】:

    你不能用interface来做,但是你可以用type来做:

    interface I_Employee {  
        id:string|number
        availableShifts: Array<string|number > | null;
        unAvailableShifts: Array<string|number > | null
        desiredNumShifts?: number | null
        minNumShifts?: number | null
        maxNumShifts?: number | null
    }
    
    type SuperEmployee<T> = I_Employee & T;
    type SuperEmployee2<T> = I_Employee & {[P in keyof T]: T[P]};
    
    const employee: SuperEmployee<{salary: number}> = {
      id: 1,
      availableShifts: [],
      unAvailableShifts: [],
      salary: 1000,
    }
    
    const employee2: SuperEmployee2<{salary: number}> = {
      id: 1,
      availableShifts: [],
      unAvailableShifts: [],
      salary: 2000,
    }
    

    【讨论】:

    • 哇,原来如此。谢谢!
    猜你喜欢
    • 2018-02-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-10
    • 2021-01-09
    • 1970-01-01
    • 2011-08-01
    • 2020-06-19
    相关资源
    最近更新 更多