Skip to content

Generics cannot be used for record construction - even when constrained #1664

Open
@bdirito

Description

@bdirito

immutable: 4.0.0-rc.10
ts: 3.2.2

function foo<T extends Object>(a: T): Record.Factory<T> {
   return class extends Record(a) {} // typescript error
}

Even though we have specified that T is, in fact, an object we get an error when passing a into Record.

You can cast to an object explicitly and

function foo<T extends Object>(a: T): Record.Factory<T> {
   return class extends Record(<Object>a) {}
}

The problem is that we loose type info inside the [ananomous] class. This becomes important when we try to extend a

class B { b: number = 1 }

function foo<T extends Object>(a: T): Record.Factory<T & B> {
   const allArgs : T & B = _.extend(new B(), a)
   return class extends Record(<Object>allArgs) {
      // because we cast to Object we loose the type info
     bar() { return this.b } // typescript error
  }
}

There are workarrounds for this in turn (public readonly b!: number) but ideally this should be covered by simply passing allArgs as it has type T & B, both of which we know to be objects.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions