使用泛型和构造函数的 TypeScript 强制转换类型



我有一个基类,以及它的子类。

这些类的实例被放入具有基类类型的集合中。

class Type extends Object {
    public static ID = 'type';
    public id = 'type';
    constructor() { super(); }
}
class TypeA extends Type {
    public static ID = 'type-a';
    public id = 'type-a';
    constructor() { super(); }
    public onlyA() { return 'only A has this method'; }
}
class TypeB extends Type {
    public static ID = 'type-b';
    public id = 'type-b';
    constructor() { super(); }
    public onlyB() { return 'only B has this method'; }
}
// Discards subclass type information:
const list: Type[] = [
    new TypeA(),
    new TypeB()
];
// Has inferred type: Type
const list0 = list[0];

现在,如果我知道正确的类型,我可以使用as来提升类型:

const list0asA = list0 as TypeA;
list0asA.onlyA();

但是,我想做的是创建一个通用函数,该函数将动态检查实例,如果不匹配,则返回提升的类型或null

我想出了以下内容,但不太正确:

function castOrNull<
    C extends typeof Type
>(value: Type, Constructor: C): C | null {
    if (value.id !== Constructor.ID) {
        return null;
    }
    return value as C;
}
const list0castA = castOrNull(list0, TypeA);
if (list0castA) {
    list0asA.onlyA();
}

问题是我没有尝试将变量转换为构造函数类型,而是该构造函数的实例的类型,因此 as 和返回类型不正确。

或者,这

确实有效,但它需要显式设置泛型类型,这意味着在使用时指定类型两次,这不太理想。

function castOrNull<
    T extends Type
>(value: Type, Constructor: typeof Type): T | null {
    if (value.id !== Constructor.ID) {
        return null;
    }
    return value as T;
}
const list0upA = castOrNull<TypeA>(list0, TypeA);
if (list0castA) {
    list0asA.onlyA();
}

是否可以在不指定类型两次的情况下创建此泛型函数?

从 Typescript 2.8 开始,InstanceType<T> 类型被添加到标准库中,该库从构造函数类型中提取T其实例的类型。因此,对于您的代码段,您可以将其用于返回类型和强制转换:

function castOrNull<
    C extends typeof Type
>(value: Type, Constructor: C): InstanceType<C> | null {
    if (value.id !== Constructor.ID) {
        return null;
    }
    return value as InstanceType<C>;
}
// All good now
const list0castA = castOrNull(list0, TypeA);
if (list0castA) {
    list0asA.onlyA();
}

最新更新