具有泛型的TypeScript对象文字类型断言

时间:2017-08-24 05:12:32

标签: typescript tslint

我有一个类似的TypeScript类:

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 || [];
      }
    }
}

问题是,这会导致tslint no-object-literal-type-assertion规则失败(this.props = {} as Props行)。如果我删除了as Props部分,则会收到{}无法分配给Props类型的错误。

如何在不禁用tslint规则的情况下进行设置?

供参考,这是预期用途:

type X = { foo: string; }

const foo = new Foo<X>({ foo: 'bar' });
const foo2 = new Foo(['']);

3 个答案:

答案 0 :(得分:1)

你能做到:

public props: Props | {}

答案 1 :(得分:0)

也许:

 this.props = new Props();

答案 2 :(得分:-1)

我认为TSLint实际上是在拯救你。让我们说警告不存在,你这样做了:

interface X { someProperty: number };
var foo = new Foo<X>(['']);
var bar: number = foo.props.someProperty;

即使someProperty不是可选的,它也会返回undefined - 事实是{}不能分配给X类型的变量而且tslint是正确的阻止你进入你的轨道。

我会重新考虑你在这里要解决的问题的方法。