您在这里看到的是一个generic class,它扩展了另一个泛型类。
typeB、typeC、typeC 和 Unknown 都是已知的预定义类型。 typeA 是一个变量。 (这个例子可以使这种区别更加清楚。)
myClass 是否“看到”了 typeA 自身?
是的! myClass 可以将 typeA 类型用于其任何方法或其他内部类型。
typeA 是否也扩展 typeC 和 typeD?
没有。在某些情况下可能是正确的,但不是必需的。 anotherClass 有两个通用变量。我们声明我们的类myClass 扩展了anotherClass 的版本,其中这些变量设置为typeC 和typeD。同样,typeC 和 typeD 是已知类型。
typeA 是 typeB 的别名吗?
不,并非总是如此。我们的变量typeA 必须是extend 已知类型typeB。它可能是 typeB 或扩展它的东西。可以在任何需要typeB 的地方使用typeA,因为我们知道typeA extends typeB。
Unknown 是变量typeA 的后备值,无法推断类型。 Unknown 也必须扩展 typeB。
希望这个例子更清楚:
// AnotherClass depends on two generics which could be anything
class AnotherClass<DataType, KeyType> {
// the generics are used here to determine the types of the instance variables
data: DataType;
key: KeyType;
// the generic values for each instance will be determined by the arguments which are passed to the constructor
constructor(data: DataType, key: KeyType) {
this.data = data;
this.key = key;
}
}
// MyInterface is some sort of known type
interface MyInterface {
myKey: string;
}
// MyClass has one generics value Name which can be a specific string or just `string`
// it extends AnotherClass where `DataType` is `MyInterface` and `KeyType` is `string`
class MyClass<Name extends string = string> extends AnotherClass<MyInterface, string> {
name: Name;
constructor(name: Name, data: MyInterface) {
// must call superclass AnotherClass's constructor
super(data, name);
this.name = name;
}
}
Typescript Playground Link