簡體   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