带有泛型的 TypeScript 对象字面量类型断言

TypeScript object literal type assertion with generics

我有一个 TypeScript class 像这样:

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(['']);

也许:

 this.props = new Props();

你能做到吗:

public props: Props | {}

我认为 TSLint 实际上是在拯救你。假设警告不存在,而你这样做了:

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

即使 someProperty 不是可选的,它也会返回 undefined - 事实上 {} 不能分配给类型 X 和 tslint 的变量正确地阻止了你。

无论您在这里尝试解决什么问题,我都会重新考虑您的方法。