Given a class Foo
class Foo {
foo: string;
bar: number;
baz: Date;
}
I want to create a generic type called Transmuted<T>
that would return this interface:
interface TransmutedFoo {
foo: any
bar: any
baz: any
}
How can I create this generic?
2
Answers
When you use
class Foo {/*...*/}
, TypeScript creates a type calledFoo
to represent instances of the class. So fundamentally, your question comes down to: How do I convert one object type to another type with the same keys?The answer is a mapped type:
[Key in keyof T]
lists the property keys ofT
, and what appears after the:
is the type for those properties. In this case, it’s a very simple mapped type since it maps everything toany
.Applying that to
Foo
gives us:Playground link
You can achieve this by creating a generic type, in this case we call it
Transmuted<T>
. This generic type will transform the properties ofT
intoany
type. See below for code on how to go about it:So we use a mapped type to iterate through each of the properties
K
ofT
using the TypeScriptkeyof
operator, and then, typeany
is assigned as the type for each of the property. Hope this helps!