i.brod
i.brod

Reputation: 4603

How to write a generic interface with mandatory properties, and any possible property from T?

Let's say i have an interface/type like that:

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
}

But, i would like the implementing employee object to have any other property that exists in a type "T". Would look something like this:

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
}

Of course i could just do [index:string]:any, instead of generics, but then Typescript does not recognize the properties, in some parts of my code. I have functions that receive certain objects and mutate them, therefore i need to be able to somehow make this generic.

Can this be done?

Upvotes: 0

Views: 396

Answers (1)

HTN
HTN

Reputation: 3594

You can't do it with interface, but you can do with 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,
}

Upvotes: 1

Related Questions