在TypeScript中将对象文字用于函数时,Intellisene无法正常工作

背景

我正在将TypeScript与Vue一起使用,并且有一个组件可以处理API的添加和编辑资源。因此,在表单提交事件中,我使用了其他方法来确定需要调用的API的类型,所以我写了:

this.$store.commit('app/setfullScreenHttpLoader',true);
if (!this.Data.Id) {
  delete this.Data.Id;
  this.Api.add(this.Data).subscribe(
    () => {
      this.$emit('save');
      this.$store.commit('app/setfullScreenHttpLoader',false);
      this.$showSuccessToaster(this.$t('add_success') as string);
    },() => {
      this.$store.commit('app/setfullScreenHttpLoader',false);
      this.$showErrorToaster(this.$t('add_error') as string);
    }
  );
} else {
  this.Api.update(this.Data).subscribe(
    () => {
      this.$emit('save');
      this.$store.commit('app/setfullScreenHttpLoader',false);
      this.$showSuccessToaster(this.$t('update_success') as string);
    },false);
      this.$showErrorToaster(this.$t('update_error') as string);
    }
  );
}

当前情况:

现在您可以在add和update方法中看到相同的代码,因此为避免代码重复,我制作了另一个函数并将类型传递为'add''edit'

public save(type: string) {
  this.Api[type](this.Data).subscribe( // <-- here I lose intellisense after [type]
    () => {
      this.$emit('save');
      this.$store.commit('app/setfullScreenHttpLoader',false);
      this.$showSuccessToaster(this.$t(`${type}_success`) as string);
    },false);
      this.$showSuccessToaster(this.$t(`${type}_error`) as string);
    }
  );
}

我需要什么

这段代码可以很好地工作,但是我失去了智能感知的能力,有什么建议可以在这里获得智能感知吗?

hopefulyatou 回答:在TypeScript中将对象文字用于函数时,Intellisene无法正常工作

我不确定在没有可重现的示例的情况下该方法是否可行,但是我的猜测是您希望type的注释不是string,而是"add" | "update"union中的string literal types,将为编译器提供信息,使他们知道this.Api[type]add()还是update()方法,并希望带给您一些帮助智能感知。像这样:

public save(type: "add" | "update") {
  this.Api[type](this.Data).subscribe( 
    () => {
      this.$emit('save');
      this.$store.commit('app/setFullScreenHttpLoader',false);
      this.$showSuccessToaster(this.$t(`${type}_success`) as string);
    },() => {
      this.$store.commit('app/setFullScreenHttpLoader',false);
      this.$showSuccessToaster(this.$t(`${type}_error`) as string);
    }
  );
}

好的,希望能有所帮助。祝你好运!

本文链接:https://www.f2er.com/3166971.html

大家都在问