Home > front end >  Update nested fields in TypeScript
Update nested fields in TypeScript

Time:02-01

I want to update every field of a given type to T | () => T. Given the following TypeScript type:

type User = {
 first: string;
 last: string;
}

Are there any utility types available, which would allow me to map User to:

{
  first: string | (() => string);
  last: string | (() => string);
}

Hope this makes sense. Thanks!

CodePudding user response:

You can use mapped type, e.g.

type Fn<T> = {
  [K in keyof T]: T[K] | (() => T[K]);
}

let user!: Fn<User>;
user.first // string | ()=>string

If you want to do it on nested fields, you can do it recursively.

  •  Tags:  
  • Related