Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeScript object literal type assertion with generics

I have a TypeScript class like so:

class Foo<Props extends {}> {
    public readonly props: Props;
    public readonly otherStuff: string[];

    constructor(properties: Props | string[], otherStuff?: string[]) {
      if (properties instanceof Array) {
        this.otherStuff = properties;
        this.props = {} as Props;
      } else {
        this.props = properties;
        this.otherStuff = otherStuff || [];
      }
    }
}

The problem is that this results in a no-object-literal-type-assertion rule failure in tslint (on the this.props = {} as Props line). If I remove the as Props part I get an error that {} isn't assignable to type Props.

How would you go about setting this up without disabling that tslint rule?

For reference, here's an expected usage:

type X = { foo: string; }

const foo = new Foo<X>({ foo: 'bar' });
const foo2 = new Foo(['']);
like image 215
Aaron Powell Avatar asked Aug 24 '17 05:08

Aaron Powell


1 Answers

Could you do:

public props: Props | {}

like image 101
Josh Wulf Avatar answered Nov 08 '22 11:11

Josh Wulf