首页 > 解决方案 > Typescript 定义类类型而不定义 JS 类?

问题描述

我想为具有某些属性的类创建一个类类型。例如:

class Cat {
  name = 'cat';
}

class Dog {
  name = 'dog';
}

type Animal = ???;

function foo(AnimalClass: Animal) {
  console.log((new AnimalClass()).name);
}

我想doSomething接受任何具有字符串name属性的类。我能做到这一点的唯一方法是:

class _Animal {
  name: string;
}

type Animal = typeof _Animal;

有没有办法在不定义新的 JS 类的情况下做到这一点?我只想要类型。

标签: javascripttypescript

解决方案


new您可以使用表达式描述构造函数:

type AnimalContructor = new () => { name: string };

function foo(AnimalClass: AnimalContructor) {
  console.log((new AnimalClass()).name);
}

操场


其他选项是定义构造函数的联合:

type AnimalContructor = typeof Cat | typeof Dog;

操场


推荐阅读