Handle undefined values(处理未定义值)¶
:::callout{theme="warning"} The following documentation is specific to TypeScript v1 functions. For more robust capabilities, including support for Ontology SDK and configurable resource requests, we recommend migrating to TypeScript v2. :::
Below are two useful patterns for handling undefined values which may be returned from accessing properties or links.
Explicit checks¶
@Function()
public getFullName(employee: Employee): string {
if (!(employee.firstName && employee.lastName)) {
throw new UserFacingError("Cannot derive full name because either first or last name is undefined.");
}
return employee.firstName + " " + employee.lastName;
}
By checking that both the firstName and lastName fields are defined, the TypeScript compiler knows that the final line with the return statement can compile correctly. The benefit of this approach is that type checking is more explicit, and in the case where undefined values are present, you can throw a more explicit error about what went wrong.
Non-null assertion operator¶
You can use the TypeScript non-null assertion operator ↗ (!) to ignore the undefined case.
@Function()
public getFullName(employee: Employee): string {
return employee.firstName! + " " + employee.lastName!;
}
This approach simply overrides the TypeScript compiler and asserts that the fields you're accessing are defined. Although this makes for more concise code, this can lead to cryptic errors in the case when one of the fields turns out to be undefined. We recommend making explicit checks when possible.
中文翻译¶
处理未定义值¶
:::callout{theme="warning"} 以下文档仅适用于 TypeScript v1 函数。如需更强大的功能(包括对 Ontology SDK 和可配置资源请求的支持),建议迁移至 TypeScript v2。 :::
以下是处理访问属性或链接时可能返回的 undefined 值的两种实用模式。
显式检查¶
@Function()
public getFullName(employee: Employee): string {
if (!(employee.firstName && employee.lastName)) {
throw new UserFacingError("无法获取全名,因为名字或姓氏未定义。");
}
return employee.firstName + " " + employee.lastName;
}
通过检查 firstName 和 lastName 字段均已定义,TypeScript 编译器能够正确编译包含 return 语句的最后一行。这种方法的优势在于类型检查更加明确,并且在存在 undefined 值的情况下,可以抛出更明确的错误信息来说明问题所在。
非空断言运算符¶
你可以使用 TypeScript 的非空断言运算符 ↗(!)来忽略 undefined 的情况。
@Function()
public getFullName(employee: Employee): string {
return employee.firstName! + " " + employee.lastName!;
}
这种方法直接覆盖 TypeScript 编译器的检查,断言所访问的字段已定义。虽然这样可以使代码更简洁,但当某个字段实际为 undefined 时,可能会导致难以理解的错误。建议在可能的情况下使用显式检查。