Node.js typescript类构造函数从构造函数参数推断类型

Node.js typescript类构造函数从构造函数参数推断类型,node.js,typescript,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 & {

比如说我有一门课是这样的:

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

我不确定如何强制typescript正确推断类实例的类型。我希望我已经提供了足够的信息来说明问题,有人知道吗?

我认为这不是一个受支持的用例。Typescript无法动态计算您创建的
实体的类型。它只知道创建了一个
实体
,并且通过类的定义,它知道
id
name
都是可选的。我不相信这是一个受支持的用例。Typescript无法动态计算您创建的
实体的类型。它只知道创建了一个
实体
,并且根据类的定义,它知道
id
name
都是可选的。