代码之家  ›  专栏  ›  技术社区  ›  Zze

如何检查函数是否存在?

  •  0
  • Zze  · 技术社区  · 6 年前

    我正在将一些旧的javascript更新为typescript。在javascript中,您可以执行以下操作 [ref] :

    if (typeof functionName === "function") { 
        // safe to use the function
        functionName();
    }
    

    在typescript中,这会导致语法错误 “找不到名称'updateradarcharts'”

    我可以用declare语句解决这个问题

    declare var functionName: Function;

    但是,这感觉不像是一个干净的解决方案,因为它可能不会声明(因此检查)。在TS中有更干净的方法来做这个吗?

    0 回复  |  直到 6 年前
        1
  •  4
  •   Evert    6 年前

    您可以将函数声明为:

    declare var functionName: Function | undefined;
    
        2
  •  1
  •   Simon Schick    6 年前

    对于全局增强(这似乎是您想要实现的),用户定义的类型保护通常工作得很好:

    interface AugmentedGlobal {
      something: SomeType;
    }
    
    function isAugmented(obj: any): obj is AugmentedGlobal {
      return 'something' in obj;
    }
    
    if (isAugmented(global/**or window*/)) {
      const myStuff = global.something;
    }
    
    推荐文章