简体   繁体   English

打字稿推断类型而不使用显式类型变量进行回调

[英]Typescript infer type without using explicit type variable for callback

I want to wrap rxjs subscribe's next callback with my function:我想用我的函数包装 rxjs subscribe 的next回调:

type Handler<T> = (value: T) => void;

export function withTryCatch<T>(callback?: Handler<T>): Handler<T> {

  return (value: T) => {
    try {
      callback?.(value);
    } catch(err) {
      // error handling
    }
  };
}

Problem with this example bellow is, that it does not automatically infer type from subscribe's next function.下面这个例子的问题是,它不会自动从 subscribe 的next函数推断类型。 In this example, user type is stated as unknown .在此示例中, user类型声明为unknown Only way how to make user desired type, is to explicitly set withTryCatch type variable T (see commented code below - withTryCatch<UserModel> ).如何使用户所需类型的唯一方法是显式设置withTryCatch类型变量 T (请参阅下面的注释代码 - withTryCatch<UserModel> )。

 store$
    .pipe(
      map(userSelector)
    )
    // .subscribe(withTryCatch<UserModel>((user) => {
    .subscribe(withTryCatch((user) => {
      // possible error code
    }));

Is there any way how to avoid using withTryCatch<UserModel> ?有什么办法可以避免使用withTryCatch<UserModel>吗?

This issue is separated from place where you use withTryCatch function, in that case it's rxjs subscribe method.这个问题与你使用withTryCatch函数的地方分开,在这种情况下它是 rxjs订阅方法。 When you just invoke it the generic T type parameter is unknown.当您调用它时,泛型T类型参数是未知的。 When you call it with some type parameter then T is of course known.当您使用某种类型参数调用它时, T当然是已知的。 You could use Typescript inferring by typing user argument like here:您可以通过键入用户参数来使用 Typescript 推断,如下所示:

withTryCatch((user: UserModel) => {

});

You need to pass callback directly to subscribe to use Typescript inferring.您需要直接传递回调以订阅使用 Typescript 推断。 Unfortunately it is impossible with that kind of wrapper function不幸的是,这种包装函数是不可能的

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM