UNPKG

1.48 kBPlain TextView Raw
1// Copyright (c) .NET Foundation. All rights reserved.
2// Licensed under the MIT License.
3
4import { AzFuncSystemError } from '../errors';
5
6/**
7 * Retrieves a property by name from an object and checks that it's not null and not undefined. It is strongly typed
8 * for the property and will give a compile error if the given name is not a property of the source.
9 */
10export function nonNullProp<TSource, TKey extends keyof TSource>(
11 source: TSource,
12 name: TKey
13): NonNullable<TSource[TKey]> {
14 const value: NonNullable<TSource[TKey]> = <NonNullable<TSource[TKey]>>source[name];
15 return nonNullValue(value, <string>name);
16}
17
18/**
19 * Validates that a given value is not null and not undefined.
20 */
21export function nonNullValue<T>(value: T | undefined | null, propertyNameOrMessage?: string): T {
22 if (value === null || value === undefined) {
23 throw new AzFuncSystemError(
24 'Internal error: Expected value to be neither null nor undefined' +
25 (propertyNameOrMessage ? `: ${propertyNameOrMessage}` : '')
26 );
27 }
28
29 return value;
30}
31
32export function copyPropIfDefined<TData, TKey extends keyof TData>(source: TData, destination: TData, key: TKey): void {
33 if (source[key] !== null && source[key] !== undefined) {
34 destination[key] = source[key];
35 }
36}
37
38export function isDefined<T>(data: T | undefined | null): data is T {
39 return data !== null && data !== undefined;
40}