我正在创建一个基类(这里称为top),我想用它来为它的所有孩子创建一个蓝图。我这样做是通过在基础上创建抽象函数,以便孩子们必须有一个实现,以便有效。这是一个例子
interface ITopData { }
abstract class top{
constructor() { }
abstract test<T extends ITopData>(data: T): void;
}
interface IBottomData extends ITopData { }
class bottom extends top {
constructor() { super() }
test<IBottomData>(data) { return }
}
这是所需的代码,但是当我写这样的课程时
class bad extends top {
constructor() { super() }
test(data: string) { return }
//these implementations also dont cause any complaints
//test<T extends string>(data) { return }
//test() { return }
}
我想要的是打字稿来抱怨班级&#34;坏&#34;并没有适当地扩展课程&#34; top&#34;。当我把它写出来的时候,虽然我没有得到我的intellisense或我的转录器的投诉。
编辑:如果子类没有任何函数实现,我会收到错误,但是在使用上面显示的任何实现时都会出错。
答案 0 :(得分:2)
要记住的一件事是string
匹配interface ITopData {}
- 因为接口没有属性,任何对象类型都会匹配它。
虽然TypeScript 2.0不会基于泛型参数强制执行类型,但如果直接指定参数的类型,则会出现编译器错误。方法参数的语义也保持不变。
interface ITopData {
// the interface must have at least one mandatory property,
// otherwise any object will match it
foo: number;
}
abstract class foo{
constructor() { }
abstract test(data: ITopData): void;
}
interface IBottomData extends ITopData { }
class bottom extends foo {
constructor() { super() }
test(data: IBottomData) { return }
}
class bad extends foo {
constructor() { super() }
test(data: string) { return; }
}
或者,指定类的泛型类型而不是方法。这样,只要类型不匹配,您也会遇到编译器错误
interface ITopData {
// the interface must have at least one mandatory property,
// otherwise any object will match it
foo: number;
}
abstract class foo<T extends ITopData>{
constructor() { }
abstract test(data: T): void;
}
interface IBottomData extends ITopData { }
class bad1 extends foo<IBottomData> {
constructor() { super() }
test(data: string) { return }
}
class bad2 extends foo<string> {
constructor() { super() }
test(data: string) { return; }
}