如何检查功能是否存在?

问题描述 投票:1回答:2

我正在将一些旧的Javascript更新为Typescript。在Javascript中,您可以执行以下[ref]

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

在Typescript中,这会出现语法错误“找不到名称'updateRadarCharts'”

我可以用声明语句来解决这个问题

declare var functionName: Function;

然而,这不是一个干净的解决方案,因为它可能不会被声明(因此检查)。在TS中有更清洁的方法吗?

typescript
2个回答
4
投票

您可以将该函数声明为:

declare var functionName: Function | undefined;

1
投票

对于全局扩充(这似乎是您想要实现的),用户定义的类型保护通常很有效:

interface AugmentedGlobal {
  something: SomeType;
}

function isAugmented(obj: any): obj is AugmentedGlobal {
  return 'something' in obj;
}

if (isAugmented(global/**or window*/)) {
  const myStuff = global.something;
}
© www.soinside.com 2019 - 2024. All rights reserved.