AnimalStrings 是 型別
export enum AnimalEnum {
Dog,
Cat,
Pig
}
type AnimalStrings = keyof typeof AnimalEnum;
// const a: AnimalStrings = 'Cat';
// TypeScript 官網寫法,但 VS Code 給我毛毛蟲
interface AnimalConstructor {
new(hp: number): AnimalInterface;
}
// 無毛毛蟲版本
export type AnimalConstructor = new(hp: number) => AnimalInterface;
interface AnimalInterface {
call(): void;
}
interface AnimalConstructor {
new(hp: number): AnimalInterface;
}
function createAnimal(ani: AnimalConstructor, hp: number): AnimalInterface {
return new ani(hp);
}
class Human implements AnimalInterface {
constructor(hp: number) {}
call() {
console.log("水之呼吸");
}
}
class Dog implements AnimalInterface {
constructor(hp: number) {}
call() {
console.log("旺旺");
}
}
let human = creatAnimal(Human, 100);
let dog = creatAnimal(Dog, 30);
改寫來源 https://www.typescriptlang.org/docs/handbook/interfaces.html#class-types