You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在不调用函数的情况下判断其返回类型(TypeScript场景)

问题描述

定义了如下TypeScript接口:

interface IClickable<T> {
  onClick: () => T|Observable<T>;
}

希望在调用onClick前判断其返回类型,伪代码如下:

private result: T|null;

public onClicked(item: IClickable<T>): void {

  if item.onClick is return type T...
    this.result = item.onClick();

  elseif item.onClick is return type Observable<T>...
    item.onClick().subscribe((result) => this.result = result)

}

请问在调用该可变返回值的函数前,正确的类型判断方式是什么?


解决方案

因为TypeScript的类型信息会在编译时被擦除,无法直接在调用函数前判断其返回类型,只能先调用函数拿到返回值,再通过运行时特征做区分,以下是两种常用的实现方式:

方式一:直接检查返回值的Observable特征

利用RxJS Observable自带的subscribe方法作为判断标识:

import { Observable } from 'rxjs';

private result: T|null;

public onClicked(item: IClickable<T>): void {
  const returnValue = item.onClick();
  
  // 检查返回值是否具备Observable的核心特征:subscribe方法
  if (typeof (returnValue as Observable<T>).subscribe === 'function') {
    (returnValue as Observable<T>).subscribe((result) => {
      this.result = result;
    });
  } else {
    this.result = returnValue as T;
  }
}

方式二:自定义类型守卫函数

通过类型守卫让TypeScript自动推导类型,代码可读性更强:

import { Observable } from 'rxjs';

// 自定义类型守卫,判断值是否为Observable
function isObservable<T>(value: T | Observable<T>): value is Observable<T> {
  return typeof (value as Observable<T>).subscribe === 'function';
}

private result: T|null;

public onClicked(item: IClickable<T>): void {
  const returnValue = item.onClick();
  
  if (isObservable(returnValue)) {
    // 此处TypeScript会自动识别returnValue为Observable<T>
    returnValue.subscribe((result) => {
      this.result = result;
    });
  } else {
    // 此处自动识别为T类型
    this.result = returnValue;
  }
}

关键说明

  • 必须先调用onClick拿到返回值才能做判断,因为编译后函数本身没有类型标识可读取。
  • 依赖subscribe方法判断是RxJS Observable的通用做法,只要是标准Observable实例都适用。

内容的提问来源于stack exchange,提问作者smartroof

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.29 09:44:59