Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

TypeScript: Change type definition of string properties to numbers

Suppose we have an interface A defined like this:

interface A = {
  firstName: string;
  lastName: string;
  createdAt: Date;
}

How can I create a generic type that for any given interface, transforms all string properties to number?

Output

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

interface B = {
  firstName: number;
  lastName: number;
  cretedAt: Date;
}

>Solution :

By using a type for B instead, you can map over the keys of A and conditionally use number if the value at that key is originally string.

interface A {
  firstName: string;
  lastName: string;
  createdAt: Date;
}
type B = {
  [K in keyof A]: A[K] extends string ? number : A[K]
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading