Search code examples
typescript

How to conditionally branch on multiple argument types


Here's my code

class ImmutableArraySlice<Type> implements Iterable<Type>
{
    private _source: Array<Type>;
    private _start: number;
    private _end: number;

    constructor(from: Array<Type> | ImmutableArraySlice<Type>, start: number = 0, end?: number)
    {
        this._source = ( /* check if type of 'from' is ImmutableArraySlice */ ) ? from._source : from;
        this._start = start;
        this._end = end ?? source.length;
    }
    ...
}

The problem is that I need to assign different things to this._source based on the input type, but I don't know how to do it. I couldn't google it as I can't formulate this well enough and, as far as I know, you can't have multiple constructors in JS/TS, so I'm out of luck here too

EDIT 1: Made changes to code to further clarify what my goals are (yes, this wasn't as obvious as I thought, my bad)


Solution

  • Yes. As was mentioned by both moonstar-x and jcalz, using instanceof was the solution I needed

    Here's the full code snippet I have now in case anyone else stumbles on this issue:

    class ImmutableArraySlice<Type> implements Iterable<Type>
    {
        private _source: Array<Type>;
        private _start: number;
        private _end: number;
    
        constructor(from: Array<Type> | ImmutableArraySlice<Type>, start: number = 0, end?: number)
        {
            const is_slice = from instanceof ImmutableArraySlice;
            this._source = (is_slice) ? from._source : from;
            this._start = (is_slice) ? from.start + start : start;
            this._end = (is_slice) ? from.start + (end ?? from.length) : from.length;
        }
        ...
    }