Skip to content

Files

Latest commit

184a630 · Jun 9, 2020

History

History
76 lines (70 loc) · 2.84 KB

type-guard.md

File metadata and controls

76 lines (70 loc) · 2.84 KB

Type Guard

A type guard is a function that returns a type predicate. Type guards are a type of data guard.

We use them in Typescript code to tell the compiler which operations are safe to perform on any piece of data of indeterminate type.

function isValue<T = any>(
    input: unknown
): input is Value<T> {
    return ((input as Value).implementsValue
        && (input as Value).implementsValue());
}

End-users rely on correctly-functioning type guards to avoid using Typescript's as XXX type casting in their code.

It's almost impossible to write a type-safe library or application without creating type guards.