Generics TypeScript中的关联类型
其中有这样的概念 这是一种泛型接口,但关联类型的一个重要特性是它们可以从包含类型的外部引用Generics TypeScript中的关联类型,generics,typescript,Generics,Typescript,其中有这样的概念 这是一种泛型接口,但关联类型的一个重要特性是它们可以从包含类型的外部引用 var x: IntStack.ItemType = someIntStack.pop() 有可能在TypeScript中生成这样的内容吗?根据,可以是这样的内容: abstract class Container<ItemType> { abstract append(item: ItemType): void; abstract count(): number;
var x: IntStack.ItemType = someIntStack.pop()
有可能在TypeScript中生成这样的内容吗?根据,可以是这样的内容:
abstract class Container<ItemType> {
abstract append(item: ItemType): void;
abstract count(): number;
abstract subscript(i: number): ItemType;
}
class IntStack extends Container<number> {
private items: Array<number> = [];
append(item: number) {
this.items.push(item);
}
count(): number {
return this.items.length;
}
subscript(i: number): number {
return this.items[i];
}
// Other functions
}
抽象类容器{
摘要追加(项:项类型):作废;
抽象计数():数字;
摘要下标(i:编号):ItemType;
}
类IntStack扩展容器{
私有项:数组=[];
追加(项目:编号){
此.items.push(item);
}
count():数字{
返回此.items.length;
}
下标(i:编号):编号{
返回此项。项目[i];
}
//其他职能
}
更新
通常,在运行时不可能获取泛型类型参数,因为typescript编译器仅将此“类型”用于类型检查,并且不会编译成结果JavaScript代码中的任何工件。你可以在网上查一下
尽管如此,如果您在运行时有一个真正的值,您可以使用一些技巧,如SO文章中所述。目前Typescript中的关联类型没有此类功能 关联类型的替代方案 虽然打字脚本中没有这样的东西
// WILL NOT COMPILE
interface Add<T> {
type Output;
add(other: T): Output;
}
//将不会编译
接口添加{
类型输出;
加(其他:T):输出;
}
有一些替代方案可以解决关联类型在不同程度上解决的一些问题
推断泛型
您可以推断传递给泛型的类型,如下所示
type ArrayItem<T> = T extends Array<infer I> ? I : never;
类型ArrayItem=T扩展数组?I:从来没有;
你可以像这样使用这种类型
const number: ArrayItem<Array<number>> = 1;
常数编号:ArrayItem
为字段的字段编制索引
假设你有这样一些类型:
type StorageStage<T> =
| { kind: 'initial' }
| { kind: 'loading', promise: Promise<Array<T>> }
| { kind: 'loaded', storage: Array<T> };
class AsyncStorage<T> {
state: StorageStage<T> = { kind: 'initial' };
}
类型StorageStage=
|{kind:'首字母'}
| {kind:'loading',promise:promise.这不是他的观点,类型可以从外部引用吗?@LukaJacobowitz,没错。我会在问题中更清楚地概括这一点。@TSV,谢谢你的努力,但是泛型类型的概念对我来说非常清楚。谢谢你的澄清,伙计们。我已经更新了answer、 这个答案可能应该被接受,因为它包含“这是不可能的”(从TypeScript v1.8开始)。
type StorageStage<T> =
| { kind: 'initial' }
| { kind: 'loading', promise: Promise<Array<T>> }
| { kind: 'loaded', storage: Array<T> };
class AsyncStorage<T> {
state: StorageStage<T> = { kind: 'initial' };
}
const storageStage: AsyncStorage<number>["state"] =
{ kind: 'loaded', storage: [1] };