omidh
omidh

Reputation: 2822

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

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

Upvotes: 0

Views: 385

Answers (2)

menme95
menme95

Reputation: 11

I would define it as a template,

interface A<T> = {
    firstName: T;
    lastName: T;
    createdAt: Date;
}

Then when you define it as a string implements A<string> or A<number>

Upvotes: 1

CertainPerformance
CertainPerformance

Reputation: 371108

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

Upvotes: 1

Related Questions