stf
stf

Reputation: 41

typescript mapped types multiple types

I have 2 types:

type UserForm = 'student' | 'teacher';
type FormFields = 'name' | 'age' | 'email';

what I want to achieve:

interface Form {
  form: {
    studentName: string;
    studentAge: string;
    studentEmail: string;
    teacherName: string;
    teacherAge: string;
    teacherEmail: string;
  }
}

I know it can be done "manually", like this, but it's not necessary linked to the UserForm type

interface {
  form: {
    [K in FormFields as `student${Capitalize<K>}`]: string
  } & {
    [K in FormFields as `teacher${Capitalize<K>}`]: string
  }
}

Upvotes: 1

Views: 75

Answers (1)

Tobias S.
Tobias S.

Reputation: 23925

A shorter way to achieve this behavior would look like this:

interface Form {
  form: {
    [K in `${UserForm}${Capitalize<FormFields>}`]: string
  }
}

Key remapping does not seem to be necessary here. We can simply use both UserForm and FormFields in the template literal type and the mapped type will use it to construct a union of all permutations.


Playground

Upvotes: 3

Related Questions