Skip to content

Latest commit

 

History

History
33 lines (26 loc) · 1018 Bytes

use-an-array-check-for-type-narrowing.md

File metadata and controls

33 lines (26 loc) · 1018 Bytes

Use An Array Check For Type Narrowing

If you are typing a concatenation function for melding two values together into a single array, you may end up with a function signature like this:

type ConcatFunction = (value: any | any[], array: any[]) => any[];

That first argument can be an individual value or an array of values. You'll need to handle both scenarios in the function implementation. Using the Array.isArray function as a type guard, you can check differentiate between those two cases.

const concat: ConcatFunction = (value, array) => {
    if(Array.isArray(value)) {
        return [...value, ...array];
    } else {
        return [value, ...array];
    }
}

concat(true, [1,2,3]);
// [true, 1, 2, 3]

concat([1,2,3], ['a', 'b', 'c'])
// [1, 2, 3, 'a', 'b', 'c']

This is a form of type narrowing.