Home > database >  TypeScript: Change type definition of string properties to numbers
TypeScript: Change type definition of string properties to numbers

Time:08-28

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

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

CodePudding user response:

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]
}
  • Related