[英]TypeScript: defining a type that specifies a new-able function
我正在寻找一种方法如何在 TypeScript 中复制以下 JavaScript 功能:
class Tree {
constructor(name) {
this.name = name;
this.type = 'unspecified';
}
grow() {
console.log(`${this.name} (${this.type}): growing.`);
}
}
class Pine extends Tree {
constructor(name) {
super(name);
this.type = 'pine';
}
somethinPiney() {
return true;
}
}
function treeMaker(treeType, name) {
return new treeType(name);
}
const t = new Tree('Noname');
const p = new Pine('Backyard');
const m = treeMaker(Pine, 'Seaside');
t.grow();
p.grow();
m.grow();
console.log(m instanceof Pine); // true
console.log(m instanceof Tree); // true
console.log(m instanceof Date); // false
更具体地说, treeMaker
function 中的treeType
参数类型。 它代表了一个新的 function。 用什么语法来描述这种类型? 以及如何指定我只对Tree
或扩展Tree
的 class 感兴趣?
在这里,您的 go 与 TypeScript 翻译尽可能接近您的 JavaScript 代码:
class Tree {
constructor(private name: string, private type = 'unspecified') {
}
grow() {
console.log(`${this.name} (${this.type}): growing.`);
}
}
class Pine extends Tree {
constructor(name: string) {
super(name, 'pine');
}
somethinPiney() {
return true;
}
}
function treeMaker<T extends Tree>(treeType: new (name: string) => T, name: string): T {
return new treeType(name);
}
const t = new Tree('Noname');
const p = new Pine('Backyard');
const m = treeMaker(Pine, 'Seaside');
t.grow();
p.grow();
m.grow();
console.log(m instanceof Pine); // true
console.log(m instanceof Tree); // true
console.log(m instanceof Date); // false
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.