skip to Main Content

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


  1. When you use class Foo {/*...*/}, TypeScript creates a type called Foo 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:

    type Transmuted<T> = {
        [Key in keyof T]: any;
    };
    

    [Key in keyof T] lists the property keys of T, 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 to any.

    Applying that to Foo gives us:

    class Foo {
        foo: string;
        bar: number;
        baz: Date;
    
        constructor() {
            this.foo = "";
            this.bar = 0;
            this.baz = new Date();
        }
    }
    
    type Transmuted<T> = {
        [Key in keyof T]: any;
    };
    
    type TransmutedFoo = Transmuted<Foo>;
    //   ^? type TransmutedFoo = { foo: any; bar: any; baz: any };
    

    Playground link

    Login or Signup to reply.
  2. You can achieve this by creating a generic type, in this case we call it Transmuted<T>. This generic type will transform the properties of T into any type. See below for code on how to go about it:

    class Foo {
      foo: string;
      bar: number;
      baz: Date;
    }
    
    type Transmuted<T> = {
      [K in keyof T]: any;
    }
    
    type TransmutedFoo = Transmuted<Foo>
    

    So we use a mapped type to iterate through each of the properties K of T using the TypeScript keyof operator, and then, type any is assigned as the type for each of the property. Hope this helps!

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search