如何编写具有强制属性的通用接口,以及来自T的任何可能属性?



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

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
}

但是,我希望实现employee对象具有存在于类型"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无法识别属性。我有接收特定对象的函数,并且改变因此,我需要能够以某种方式使其泛型。

这能做到吗?

你不能用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,
}

相关内容

最新更新