Typescript 在类初始值设定项中使用异步代码分配属性时出现问题 我所拥有的

Typescript 在类初始值设定项中使用异步代码分配属性时出现问题 我所拥有的,typescript,Typescript,我有一个类只在其构造函数中执行异步代码,其他代码依赖于异步代码结果。根据一些答案,要在类构造函数中执行异步代码,我可以遵循以下两种路径之一,在上运行异步代码或使用 无论采用哪种路径,我都必须创建一些具有异步操作结果的类属性 我所尝试的: 1.创建静态异步工厂函数 class-MyClass{ 私有构造函数(){ //这里没有异步调用 } 静态异步创建( 某些参数, 另一个参数, ) { const myClass=new myClass(); const foo=等待某物(someParamet

我有一个类只在其构造函数中执行异步代码,其他代码依赖于异步代码结果。根据一些答案,要在类构造函数中执行异步代码,我可以遵循以下两种路径之一,在上运行异步代码或使用

无论采用哪种路径,我都必须创建一些具有异步操作结果的类属性

我所尝试的: 1.创建静态异步工厂函数
class-MyClass{
私有构造函数(){
//这里没有异步调用
}
静态异步创建(
某些参数,
另一个参数,
) {
const myClass=new myClass();
const foo=等待某物(someParameter);
//创建一些具有异步操作结果的类属性
myClass.property=foo;
返回myClass;
}
}
//有了这个,我可以创建一个
const myClass=等待myClass.create(x,y)
此方法的问题是,如果我尝试访问使用异步结果创建的类属性,如:
myClass.property
,TS编译器抛出错误
TS2339:类型“myClass”上不存在属性“property”
。另一件事是ESLint由于空构造函数而引发错误:
ESLint:意外的空构造函数。

2.使用init方法 通过这种方法,我可以访问
的asign属性:

class-MyClass{
属性:SomeType;
构造函数(){
//这里没有异步调用
}
异步初始化(
某些参数,
另一个参数,
) {
const foo=等待某物(someParameter);
//创建一些具有异步操作结果的类属性
this.property=foo;
归还这个;
}
}
//有了这个,我可以创建一个
const currentClass=新的MyClass();
const myClass=await currentClass.init(x,y);
通过这种方法,我创建了一个字段以避免问题
TS2339:类型“MyClass”上不存在属性“Property”。
但引发了一些新问题:
TS2564:属性“Property”没有初始值设定项,并且没有在构造函数中明确指定。
构造函数为空的问题仍然存在

问题 鉴于上述情况,我不知道在初始化类并使用异步结果创建属性时,运行异步代码的正确方法是什么。如果将构造函数留空,则会出现上述错误,如果创建字段时没有构造函数,也会出现同样的情况

更新1 我正在处理的具体案例如下:

//构造函数中包含异步代码的当前类
类Api{
/* 
*第一个问题:
*
*我将根据crate/init方法上的异步结果创建一些属性。
*此操作的问题是引发以下错误:
*`S2564:属性'auth'没有初始值设定项,也不是绝对的
*在构造函数中赋值。`对所有字段重复此错误。此
*无法在构造函数中分配属性,因为所有属性都是
*使用异步结果值在create/init方法上创建。
*/
auth:AuthAPI;
签出:CheckoutAPI;
cart:CartAPI;
类别:CategoriesAPI;
收藏:CollectionsAPI;
产品:ProductsAPI ;;
/*第一个问题::`ESLint:意外的空构造函数`
*因为我没有任何要同步创建的属性,
*我最终得到了一个空构造函数。
*/
私有构造函数(){}
//静态工厂函数,用于在类初始化时执行异步代码,可以用“init method”替换,以获得相同的结果:在初始化类时执行异步代码。
静态异步创建(
//配置值
客户:阿波罗客户,
config:ConfigInput,
onStateUpdate?:()=>任何,
):承诺{
常量api=新api();
常量最终配置={
…默认配置,
…配置,
};
const localStorageHandler=new localStorageHandler();
const apolloClientManager=新apolloClientManager(客户机);
const jobsManager=等待jobsManager.create(
localStorageHandler,
阿波罗客户经理,
);
//等待的异步类/方法
const salerstate=等待salerstate.create(
最终配置,
localStorageHandler,
阿波罗客户经理,
职业经理人,
);
const localStorageManager=新的localStorageManager(
localStorageHandler,
saleorState,
);
如果(状态更新){
saleorState.SubscribeTonitifiedChanges(onStateUpdate);
}
//创建具有异步结果的属性
api.auth=新的AuthAPI(销售状态、作业管理者、最终配置);
api.checkout=新SaleorCheckoutAPI(saleorState,作业管理者);
api.cart=新的SaleorCartAPI(
localStorageManager,
阿波罗客户经理,
saleorState,
职业经理人,
);
api.categories=新类别api(客户);
api.collections=新的CollectionsAPI(客户);
api.products=新产品SAPI(客户);
//返回已创建属性的类
返回api;
}
}
//创建类并等待结果
const myApi=等待Api.clater(
阿波罗客户,
配置,
onSaleorApiChange,
);
/*
*第三个问题:这里我访问了一些用异步代码创建的属性,
*根据类字段部分中的注释,
*我正在处理一些字段问题,因为如果我没有构造函数,
*属性给我上面提到的'TS error',如果我删除
*字段和使用方法2,其中我使用`init方法`
*访问“this”,当我试图访问类属性时,
*我发现错误'TS2339:类型'Api'上不存在属性'auth'`
*/
const auth=myApi.auth()
通过上面的具体示例,我如何解决:

  • 第一个问题
    TS问题
    带有
    类字段
  • 第二个问题:如何管理
    空构造函数
  • (async () => { class MyClass { property: number; constructor(foo: number) { this.property = foo; } static async create() { const foo = await Promise.resolve(10); const myClass = new MyClass(foo); return myClass; } } const myClass = await MyClass.create() })();
class Api {
    api: AuthAPI;
    // etc
    private constructor(api: AuthAPI, /* etc */) {
        this.api = api;
    }

    // Static factory function to execute async code on class initialization, this can be replaced with `init method` to get the same result: execute asynchronous code when the class is initialised.
    static async create(
        // Configuration values 
        client: ApolloClient<any>,
        config: ConfigInput,
        onStateUpdate?: () => any,
    ): Promise<Api> {
        const finalConfig = {
            ...defaultConfig,
            ...config,
        };
        const localStorageHandler = new LocalStorageHandler();
        const apolloClientManager = new ApolloClientManager(client);
        const jobsManager = await JobsManager.create(
            localStorageHandler,
            apolloClientManager,
        );

        // Async classes/methods to await 
        const saleorState = await SaleorState.create(
            finalConfig,
            localStorageHandler,
            apolloClientManager,
            jobsManager,
        );
        const localStorageManager = new LocalStorageManager(
            localStorageHandler,
            saleorState,
        );

        if (onStateUpdate) {
            saleorState.subscribeToNotifiedChanges(onStateUpdate);
        }

        return new Api(
            // Create properties with async results
            new AuthAPI(saleorState, jobsManager, finalConfig),
            new SaleorCheckoutAPI(saleorState, jobsManager),
            new SaleorCartAPI(
                localStorageManager,
                apolloClientManager,
                saleorState,
                jobsManager,
            ),
            new CategoriesAPI(client),
            new CollectionsAPI(client),
            new ProductsAPI(client),
        });
    }
}
class Api {
    auth: number;
    private constructor(auth: number) {
        this.auth = auth;
    }
    static async create(): Promise<Api> {
        const auth = await Promise.resolve(5);
        return new Api(auth );
    }
}
(async () => {
    const myApi = await Api.create();
    const result = myApi.auth + 5;
})();
return {
    // Create properties with async results
    auth: new AuthAPI(saleorState, jobsManager, finalConfig),
    checkout: new SaleorCheckoutAPI(saleorState, jobsManager),
    cart: new SaleorCartAPI(
        localStorageManager,
        apolloClientManager,
        saleorState,
        jobsManager,
    ),
    categories: new CategoriesAPI(client),
    collections: new CollectionsAPI(client),
    products: new ProductsAPI(client),
};
property?: SomeType
property: Promise<SomeType>;
property: Promise<SomeType> | SomeType;
property: SomeType;