我正在将一些旧的Javascript更新为Typescript。在Javascript中,您可以执行以下[ref]:
if (typeof functionName === "function") {
// safe to use the function
functionName();
}
在Typescript中,这会出现语法错误“找不到名称'updateRadarCharts'”
我可以用声明语句来解决这个问题
declare var functionName: Function;
然而,这不是一个干净的解决方案,因为它可能不会被声明(因此检查)。在TS中有更清洁的方法吗?
您可以将该函数声明为:
declare var functionName: Function | undefined;
对于全局扩充(这似乎是您想要实现的),用户定义的类型保护通常很有效:
interface AugmentedGlobal {
something: SomeType;
}
function isAugmented(obj: any): obj is AugmentedGlobal {
return 'something' in obj;
}
if (isAugmented(global/**or window*/)) {
const myStuff = global.something;
}