yihereg819
yihereg819

Reputation: 141

Can't see property of typescript mixins

I can't see (vs code/whisper) id of my property when I am using mixins.

My code is:

class User {
    // @ts-ignore
    id: number;
} 

function Parent<TBase>(Base: TBase) {
  return class ParentChild {  
    _object: TBase;

    constructor (o: TBase) {
        this._object = o;
    } 

    dump(): void {
        console.log(this._object);
    }
  };
}

class Test extends Parent(User) {

}

const o = {id: 2} as any;
const i = new Test(o);

// problem
console.log(i._object.id);

Problem is on console.log(i._object.id); line. I am getting an error: Property 'id' does not exist on type 'typeof User'.

What is wrong and how can I fix it?

Upvotes: 3

Views: 339

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1074266

By passing Base as a parameter, you're using typeof User (the constructor function type) as TBase rather than User (the type of User instances). I think you just want User, by specifying the generic argument:

class User {
    // @ts-ignore
    id: number;
} 

function Parent<TBase>() {
//             ^^^^^^^^^
  return class ParentChild {  
    _object: TBase;

    constructor (o: TBase) {
        this._object = o;
    } 

    dump(): void {
        console.log(this._object);
    }
  };
}

class Test extends Parent<User>() {
//                 ^^^^^^^^^^^^^^

}

const o = {id: 2} as any;
const i = new Test(o);

// problem
console.log(i._object.id);

Playground link

A couple of other notes:

  • There's no need for the as any on o.
  • Side note: If you just want the shape of User without implementation, use interface User { id: number; } instead of class. Then you won't need the @ts-ignore. Playground link.

Upvotes: 4

Related Questions