7

I've got this typescript class that requires a generic type to be provided on construction:

type Partial<T> = {
  [P in keyof T]?: T[P];
};

class Foo<Bar> {
  bis: Partial<Bar> = {}; // (1)
  constructor() {
    console.log(typeof this.bis);  // object
    this.bis = {...this.bis};  // (2) Spread types may only be created from object types
  }
}

How ever, as you can see above, i don't get an error at (1), but i do at (2).
Why is this? And how do i fix it?

Edit1:
I've opened an issue over at the Typescript github.

Olian04
  • 6,480
  • 2
  • 27
  • 54
  • Seems like limitation on current version of TS. I would suggest you to open an issue directly at https://github.com/Microsoft/TypeScript/issues – unional Jul 23 '17 at 19:11
  • No need to create a new issue; I think this will be [fixed](https://github.com/Microsoft/TypeScript/issues/10727) as of TS v2.5 – jcalz Jul 23 '17 at 19:28
  • @jcalz, not fixed yet :( – Qwertiy Mar 28 '18 at 16:59
  • Yes, it seems that it got moved 2.5 to 2.6, to 2.7... to 2.8... to "Future". Oh well. – jcalz Mar 28 '18 at 17:50

1 Answers1

1

A workaround for this is typecasting the object explicitely with <object>,<any> or <Bar> in your case.

I don't know if your requirements allow this or not but have a look -

type Partial<T> = {
  [P in keyof T]?: T[P];
};
class Foo<Bar> {
  bis: Partial<Bar> = {}; // (1)
  constructor() {
    console.log(typeof this.bis);  // object
    this.bis = {...<Bar>this.bis};  
  }
}
Faizal Shap
  • 1,680
  • 1
  • 11
  • 26