Skip to content

Latest commit

 

History

History
126 lines (76 loc) · 3.27 KB

File metadata and controls

126 lines (76 loc) · 3.27 KB

my-awesome-typescript-project


my-awesome-typescript-project / src/code-narrowing

src/code-narrowing

Code narrowing.

Table of contents

1. Basic narrowing

whichPrimitiveType()

function whichPrimitiveType(v): string;

Defined in: src/code-narrowing.ts:26

typeof and instanceof based narrowing

Parameters

Parameter Type
v

Returns

string

Remarks

2. Predicate-based narrowing

isExtended()

function isExtended(o): o is extendedShape;

Defined in: src/code-narrowing.ts:59

Type predicate

Parameters

Parameter Type
o

Returns

o is extendedShape

Remarks

  • Cannot extract declaration : the type predicate must be present in the function signature.
  • If isExtended returns a boolean, o cannot be narrowed to extendedShape (see below).

runPredicate()

function runPredicate(o): symbol;

Defined in: src/code-narrowing.ts:73

Narrowing with predicate

Parameters

Parameter Type
o

Returns

symbol

Remarks

  • 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 this with type predicates for narrowing.

3. Union-based narrowing

processEvent()

function processEvent(o): string;

Defined in: src/code-narrowing.ts:88

Narrowing with discriminated unions

Parameters

Parameter Type
o event

Returns

string

Remarks

  • This allows DRY for similar types and code narrowing in functions that accept the union as a parameter.
  • o evaluates to never in the default case.