Office 脚本中的 TypeScript 限制
Office 脚本使用 TypeScript 语言。 在大多数情况下,任何 TypeScript 或 JavaScript 代码都将在 Office 脚本中工作。 但是,代码编辑器强制实施一些限制,以确保脚本在 Excel 工作簿中一致且按预期运行。
Office 脚本中没有“任何”类型
写入 类型 在 TypeScript 中是可选的,因为可以推断类型。 但是,Office 脚本要求变量不能为 任何类型。 Office 脚本中不允许同时使用显式和隐式 any
。 这些情况报告为错误。
明确 any
不能在 Office 脚本中将变量显式声明为类型 any
, (即 let value: any;
) 。 由 Excel 处理时,类型 any
会导致问题。 例如, Range
需要知道值是 string
、 number
或 boolean
。 如果在脚本中将任何变量显式定义为 any
类型,则运行脚本之前,将收到编译时错误 (错误) 。
在上一张屏幕截图中, [2, 14] Explicit Any is not allowed
指示第 #2 行,第 14 列定义 any
类型。 这有助于查找错误。
若要解决此问题,请始终定义变量的类型。 如果不确定变量的类型,可以使用 联合类型。 这对于保存Range
值的变量非常有用,这些变量可以是 、 number
或 boolean
类型string
, (值的类型Range
是以下类型的并集: string | number | boolean
) 。
隐 式 any
可以 隐式 定义 TypeScript 变量类型。 如果 TypeScript 编译器无法确定变量的类型 (因为类型未显式定义,或者无法) 类型推理,则它是隐式 any
的,你将收到编译时错误。
任何隐式 any
的最常见情况是在变量声明中,例如 let value;
。 有两种方法可以避免这种情况:
- 将变量分配给隐式可识别类型 (
let value = 5;
或let value = workbook.getWorksheet();
) 。 - 显式键入变量 (
let value: number;
)
无继承 Office 脚本类或接口
在 Office 脚本中创建的类和接口无法 扩展或实现 Office 脚本类或接口。 换句话说,命名空间中的 ExcelScript
任何内容都不能有子类或子接口。
不兼容的 TypeScript 函数
不能在以下项中使用 Office 脚本 API:
eval
不支持
出于安全原因,不支持 JavaScript eval 函数 。
受限标识符
以下字词不能用作脚本中的标识符。 它们是保留条款。
Excel
ExcelScript
console
仅数组回调中的箭头函数
脚本只能在为 Array 方法提供回调参数时使用箭头函数。 不能将任何类型的标识符或“传统”函数传递给这些方法。
const myArray = [1, 2, 3, 4, 5, 6];
let filteredArray = myArray.filter((x) => {
return x % 2 === 0;
});
/*
The following code generates a compiler error in the Office Scripts Code Editor.
filteredArray = myArray.filter(function (x) {
return x % 2 === 0;
});
*/
ExcelScript
不支持类型和用户定义类型的并集
Office 脚本在运行时从同步代码块转换为异步代码块。 通过 承诺 与工作簿的通信对脚本创建者是隐藏的。 此转换不支持包含ExcelScript
类型和用户定义类型的联合类型。 在这种情况下, Promise
将返回到脚本,但 Office 脚本编译器不期望它,并且脚本创建者无法与 Promise
交互。
下面的代码示例显示了 和 自定义MyTable
接口之间的ExcelScript.Table
不受支持的联合。
function main(workbook: ExcelScript.Workbook) {
const selectedSheet = workbook.getActiveWorksheet();
// This union is not supported.
const tableOrMyTable: ExcelScript.Table | MyTable = selectedSheet.getTables()[0];
// `getName` returns a promise that can't be resolved by the script.
const name = tableOrMyTable.getName();
// This logs "{}" instead of the table name.
console.log(name);
}
interface MyTable {
getName(): string
}
构造函数不支持 Office 脚本 API 和 console
语句
console
语句和许多 Office 脚本 API 需要与 Excel 工作簿同步。 这些同步使用 await
脚本的已编译运行时版本中的 语句。 await
构造函数中不支持 。 如果需要具有构造函数的类,请避免在这些代码块中使用 Office 脚本 API 或 console
语句。
以下代码示例演示了此方案。 它生成一个错误,指出 failed to load [code] [library]
。
function main(workbook: ExcelScript.Workbook) {
class MyClass {
constructor() {
// Console statements and Office Scripts APIs aren't supported in constructors.
console.log("This won't print.");
}
}
let test = new MyClass();
}
性能警告
如果脚本可能有性能问题,则代码编辑器的 linter 会发出警告。 提高 Office 脚本的性能中介绍了案例及其解决方法。
外部 API 调用
有关详细信息 ,请参阅 Office 脚本中的外部 API 调用支持 。