Alexander Zeitler
Alexander Zeitler

Reputation: 13119

Add properties to type from existing type

I have a type

type Customer = {
  firstName: string
  lastName: string
}

Is it possible to create a type EditableCustomer from this type which looks like this?

type EditableCustomer = {
  firstName: string
  lastName: string
  onFirstNameChange: (e: ChangeEvent<HTMLInputElement>) => void
  onLastNameChange: (e: ChangeEvent<HTMLInputElement>) => void
}

I'm thinking of a syntax like this:

const customer:Customer = { firstName: 'John', lastName: 'Doe' }
const editable: Editable<Customer> = customer

Upvotes: 4

Views: 2244

Answers (2)

Ivan V.
Ivan V.

Reputation: 8111

Something like this:

type Customer = {
  firstName: string
  lastName: string
}

type EditableCustomer = {
  firstName: string
  lastName: string
  onFirstNameChange: (e: ChangeEvent<HTMLInputElement>) => void
  onLastNameChange: (e: ChangeEvent<HTMLInputElement>) => void
}

type Editable<T> = EditableCustomer & T

const editable: Editable<Customer> = customer

Type Editable will hold all the properties of the EditableCustomer and also be extended with all the properties of T

Upvotes: 1

You can achieve it with help of Key Remapping

type ChangeEvent<T> = T

type EditableCustomer = {
    firstName: string
    lastName: string
    onFirstNameChange: (e: ChangeEvent<HTMLInputElement>) => void
    onLastNameChange: (e: ChangeEvent<HTMLInputElement>) => void
}


type Extend<T extends Record<string, unknown>> = keyof T extends string ? T & {
    [Prop in keyof T as `on${Capitalize<Prop & string>}Change`]: (e: ChangeEvent<HTMLInputElement>) => void
} : never

type Result = Extend<Customer>

See this line on${Capitalize<Prop & string>}Change

Upvotes: 2

Related Questions