Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unexpected "Spread types may only be created from object types" error when using generics

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.

like image 317
Olian04 Avatar asked Jul 23 '17 18:07

Olian04


1 Answers

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};  
  }
}
like image 130
Steve Avatar answered Sep 29 '22 21:09

Steve