在 TypeScript 中返回类(= 类构造函数)的工厂函数 [英] Factory functions that return classes (= class constructors) in TypeScript

查看:53
本文介绍了在 TypeScript 中返回类(= 类构造函数)的工厂函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我在 TypeScript 中以如下方式定义一个类

If I define a class in the following way in TypeScript

class A {}

那么 A 既是值又是类型,所以我可以两种方式使用它:

then A is both a value and a type, so I can use it in both ways:

type B = A
const C = A

如果 A 是一个花哨的类工厂函数的结果:

If A would be the result of a fancy class factory function instead:

const A = fancyClassFactory(...someArgs)

那么 A 只是一个值,而不是一个类型......

then A is only a value, NOT a type ...

有什么方法可以使用这样的类工厂函数,同时还可以获取类的类型?

Are there any ways to use such a class factory function and also get the type of the class?

非常感谢.

推荐答案

假设 A 是类的构造函数,您可以使用 InstanceType 条件来获取类的类型实例:

Assuming A is the constructor to the class you can use the InstanceType conditional to get the type of the instance:

const A = fancyClassFactory(...someArgs)
type A = InstanceType<typeof A>

对于@daniel-hilgarth 的具体示例,您可以使用条件类型,因此根据传入的常量返回类型是不同的:

For the specific example @daniel-hilgarth provided you could use conditional types so the return type is different according to the passed in constant:

function fancyClassFactory<T extends 'a' | 'b'>(what: T) : (T extends 'a' ? typeof fancyClassFactory.A: typeof fancyClassFactory.B) 
function fancyClassFactory(what: string) {
    if (what === 'a') {
        return  fancyClassFactory.A
    }
    if (what === 'b') {
        return fancyClassFactory.B
    }
}

namespace fancyClassFactory {
    export class A {
        foo() { return 'barA'; }
    }
    export class B {
        bar() { return 'fooB'; }
    }
} 
const A = fancyClassFactory('a');
const B = fancyClassFactory('b');
type TA = InstanceType<typeof A>;

function generic<T>(t: T) {
    console.log(t);
}

generic<TA>(new A());
generic<TA>(new B());

这篇关于在 TypeScript 中返回类(= 类构造函数)的工厂函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆