0

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

2 Answers 2

1

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]
}
Sign up to request clarification or add additional context in comments.

Comments

1

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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.