Typescript 如何指定参数将是对象

Typescript 如何指定参数将是对象,typescript,Typescript,我需要告诉我的函数实体是一个对象任何对象: 但如果我这样做: export function processEntityTags(entity: object) { entity.label; } 它表示类型对象上不存在属性标签 此实体变量可以具有不同的属性,因此我无法实现实体接口 所以我的问题是,我如何判断我的程序实体将是任何类型的对象?您可以定义一个具有如下索引签名的接口,该接口的值为任何类型 然后将接口作为参数的类型传递,这样函数只接受{}作为输入参数,如下所示 export f

我需要告诉我的函数实体是一个对象任何对象:

但如果我这样做:

export function processEntityTags(entity: object) {
    entity.label;
}
它表示类型对象上不存在属性标签

此实体变量可以具有不同的属性,因此我无法实现实体接口


所以我的问题是,我如何判断我的程序实体将是任何类型的对象?

您可以定义一个具有如下索引签名的接口,该接口的值为任何类型

然后将接口作为参数的类型传递,这样函数只接受{}作为输入参数,如下所示

export function processEntityTags(entity: Itest) {
      entity.label;
}

const t = processEntityTags({label:5}); // no error

const t = processEntityTags(6);// error

工作演示:

尽管其他答案已经在创建一个可以定义为任何属性的接口的过程中出现了,但这种类型的接口违背了使用typescript的目的

你说一个实体可以有不同的属性,所以一个接口不能工作。每种类型的实体都必须具有一些共享属性,以允许将它们传递到同一个函数中,这样您就可以使用来正确地键入这些属性

// Create a basic interface that has the label property
interface TaggableEntity{
  label: string
}

// Extend the taggable interface
interface TypeAEntity extends TaggableEntity{
  typea: string;
}

interface TypeBEntity extends TaggableEntity{
  typeb: string;
}

// Accept a Taggable Entity
function processEntityTags(entity: TaggableEntity) {
  entity.label; // Fine
  entity.typea; // Not Fine, `typea` does not exist on `TaggableEntity`
}

const typea: TypeAEntity = {
  typea: 'foo';
}

const typeb: TypeBEntity = {
  typeb: 'bar';
} 

// Although of different types both types inherit from the type accepted by the function.
processEntityTags(typea);
processEntityTags(typeb);

您可以使用实体:anyWhy为什么不使用接口?只需在界面上使用duck键入,即可使用所需的属性。请检查我的答案是否符合您的要求。
// Create a basic interface that has the label property
interface TaggableEntity{
  label: string
}

// Extend the taggable interface
interface TypeAEntity extends TaggableEntity{
  typea: string;
}

interface TypeBEntity extends TaggableEntity{
  typeb: string;
}

// Accept a Taggable Entity
function processEntityTags(entity: TaggableEntity) {
  entity.label; // Fine
  entity.typea; // Not Fine, `typea` does not exist on `TaggableEntity`
}

const typea: TypeAEntity = {
  typea: 'foo';
}

const typeb: TypeBEntity = {
  typeb: 'bar';
} 

// Although of different types both types inherit from the type accepted by the function.
processEntityTags(typea);
processEntityTags(typeb);