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

1

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.

Polydeuces answered 23/7, 2017 at 18:2 Comment(4)
Seems like limitation on current version of TS. I would suggest you to open an issue directly at github.com/Microsoft/TypeScript/issuesDecomposer
No need to create a new issue; I think this will be fixed as of TS v2.5Adulate
@jcalz, not fixed yet :(Teledu
Yes, it seems that it got moved 2.5 to 2.6, to 2.7... to 2.8... to "Future". Oh well.Adulate
A
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};  
  }
}
Anisometropia answered 14/8, 2018 at 2:24 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.