
As of TypeScript 3.7, TypeScript supports [Assert Functions](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-7.html#assertion-functions). This change adds assert types to our `assert*` functions. We can't fully take advantage of this due to [Assert functions do not constraint type when they are guarded by a truthy expression.](https://github.com/microsoft/TypeScript/issues/37295) PR Close #35964
46 lines
2.0 KiB
TypeScript
46 lines
2.0 KiB
TypeScript
/**
|
|
* @license
|
|
* Copyright Google Inc. All Rights Reserved.
|
|
*
|
|
* Use of this source code is governed by an MIT-style license that can be
|
|
* found in the LICENSE file at https://angular.io/license
|
|
*/
|
|
|
|
import {assertDefined, assertEqual} from '../util/assert';
|
|
|
|
import {TContainerNode, TElementContainerNode, TElementNode, TIcuContainerNode, TNode, TNodeType, TProjectionNode} from './interfaces/node';
|
|
|
|
export function assertNodeType(
|
|
tNode: TNode, type: TNodeType.Container): asserts tNode is TContainerNode;
|
|
export function assertNodeType(
|
|
tNode: TNode, type: TNodeType.Element): asserts tNode is TElementNode;
|
|
export function assertNodeType(
|
|
tNode: TNode, type: TNodeType.ElementContainer): asserts tNode is TElementContainerNode;
|
|
export function assertNodeType(
|
|
tNode: TNode, type: TNodeType.IcuContainer): asserts tNode is TIcuContainerNode;
|
|
export function assertNodeType(
|
|
tNode: TNode, type: TNodeType.Projection): asserts tNode is TProjectionNode;
|
|
export function assertNodeType(tNode: TNode, type: TNodeType.View): asserts tNode is TContainerNode;
|
|
export function assertNodeType(tNode: TNode, type: TNodeType): asserts tNode is TNode {
|
|
assertDefined(tNode, 'should be called with a TNode');
|
|
assertEqual(tNode.type, type, `should be a ${typeName(type)}`);
|
|
}
|
|
|
|
export function assertNodeOfPossibleTypes(tNode: TNode, ...types: TNodeType[]): void {
|
|
assertDefined(tNode, 'should be called with a TNode');
|
|
const found = types.some(type => tNode.type === type);
|
|
assertEqual(
|
|
found, true,
|
|
`Should be one of ${types.map(typeName).join(', ')} but got ${typeName(tNode.type)}`);
|
|
}
|
|
|
|
function typeName(type: TNodeType): string {
|
|
if (type == TNodeType.Projection) return 'Projection';
|
|
if (type == TNodeType.Container) return 'Container';
|
|
if (type == TNodeType.IcuContainer) return 'IcuContainer';
|
|
if (type == TNodeType.View) return 'View';
|
|
if (type == TNodeType.Element) return 'Element';
|
|
if (type == TNodeType.ElementContainer) return 'ElementContainer';
|
|
return '<unknown>';
|
|
}
|