Typescript类构造函数根据构造函数参数推断类型

时间:2020-07-30 06:56:48

标签: node.js typescript

假设我有一个这样的班级:

class Entity {
  id?: string;
  name?: string;
  constructor({ id, name }: { id?: string; name?: string }) {
    this.id = id;
    this.name = name;
  }
}

然后我有一个像这样的函数,它需要一个Entity类型的参数,但设置了id属性字段:

function myFunc(entity: Entity & { id: string }) {
  console.log("do something", entity.id);
}

我希望以下方法能起作用,但不能:

const myEntityWithoutID = new Entity({ name: "no id" });

const myEntityWithID = new Entity({ name: "dummy", id: "dummy" });

myFunc(myEntityWithoutID); // error, as expected

myFunc(myEntityWithID); // error, but this should work

我不确定如何强制打字稿正确推断类实例的类型。我希望我已经提供足够的信息来解决这个问题,有人知道吗?

0 个答案:

没有答案
相关问题