my-awesome-typescript-project / src/code-narrowing
Code narrowing.
function whichPrimitiveType(v): string;Defined in: src/code-narrowing.ts:26
typeof and instanceof based narrowing
| Parameter | Type |
|---|---|
v |
string
- Test argument value against all supported types.
- Refer to the handbook for the supported narrowing patterns.
function isExtended(o): o is extendedShape;Defined in: src/code-narrowing.ts:59
Type predicate
| Parameter | Type |
|---|---|
o |
o is extendedShape
- Cannot extract declaration : the type predicate must be present in the function signature.
- If
isExtendedreturns a boolean, o cannot be narrowed toextendedShape(see below).
function runPredicate(o): symbol;Defined in: src/code-narrowing.ts:73
Narrowing with predicate
| Parameter | Type |
|---|---|
o |
symbol
- Using predicates is part of building an efficient type system.
- The commented pattern is an equivalent implementation but considered unsafe by the compiler.
- As a result, type assertions should be paired with predicates as often as possible.
- See also assertion based narrowing for node typescript.
- See also this example that combines
thiswith type predicates for narrowing.
function processEvent(o): string;Defined in: src/code-narrowing.ts:88
Narrowing with discriminated unions
| Parameter | Type |
|---|---|
o |
event |
string
- This allows DRY for similar types and code narrowing in functions that accept the union as a parameter.
oevaluates toneverin the default case.