繁体   English   中英

Typescript 定义 class 类型而不定义 JS class?

[英]Typescript define class type without defining a JS class?

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

class Cat {
  name = 'cat';
}

class Dog {
  name = 'dog';
}

type Animal = ???;

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

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

class _Animal {
  name: string;
}

type Animal = typeof _Animal;

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

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

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

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

操场


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

type AnimalContructor = typeof Cat | typeof Dog;

操场

您可以在这里使用 generics 。 我创建了一个类型,使该类型只能分配给 object,名称属性为字符串,然后我添加了一个扩展 Animal 类型的泛型类型。 这样您就不必为 Animal 创建一个新的 class。

 class Cat { name = "cat"; age = 2; } class Dog { name = 'dog'; } class Car { brand = "Audi"; } type Animal = {name: string}; function doSomething<T extends Animal>(animal: T) { } doSomething(new Dog()); doSomething(new Cat()); doSomething(new Car()); // typescript error car is missing name

如果你想让 Animal 类型扩展另一个 class 你可以使用intersection

 class Cat { name = "cat"; age = 2; } class Information { year = 2020; } class Dog extends Information { name = 'dog'; } type Animal = { name: string } & Information; function doSomething<T extends Animal>(animal: T) { } doSomething(new Dog()); doSomething(new Cat()); // typescript error cat is missing year

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM