Below are two useful patterns for handling undefined values which may be returned from accessing properties or links.
Explicit checks
Copied!
1
2
3
4
5
6
7
@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.
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.