Jake
Jake

Reputation: 422

Typescript: how do you create a Copy of a type but change the property typeings

I want to create 2 types for an object. A type for the object itself and a type for the validation errors. These two types will have the same property names but the properties will have different typings.

type Person = {
  name: string,
  age: number,
  married: boolean
}

type PersonValidationError = {
  name?: string,
  age?: string,
  married?: string
}

After a user fills out a form constructing a Person object I want to then run it through some validation and if there are errors I want to create the error object which will have error messages in the respective property. Is there a way I can tie the PersonValidationError to the Person type itself so that when i add more properties to Person I dont need to worry about them getting out of sync.

My first thought was to use keyof

type PersonValidationError = {
  [prop: keyof Person]: string
}

But this is not valid and keyof cant be used in a index signature to my understanding.

Also I know the PersonValidationError has all its properties marked as optional but its fine if I cant change the requirement of the props because I could always wrap it in a Partial<>

Upvotes: 5

Views: 6701

Answers (1)

jcalz
jcalz

Reputation: 327624

Use a mapped type; it looks similar to an index signature but it uses the in keyword:

type PersonValidationError = { [K in keyof Person]?: string }

The ? makes the properties optional. Hope that helps; good luck!

Playground link to code

Upvotes: 13

Related Questions