Reputation: 2822
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
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
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