Define Dynamic type to array in typescript

Viewed 2287

I have an class which contain array.

let object=new DynamicARRAY()
object.add(12)
object.add("google") // This should not allowed

let object=new DynamicARRAY()
object.add("google")
object.add(12) // This should not allowed

once i set type of and array how it can maintain type of that array.

i have some thing like that

class DynamicArray {
    add(value:string):Array<number>
    add(value:number):Array<string>

    add<T>(value:T):Array<T> {
        let collection = new Array<T>()        
        collection.push(value)
        return collection
    }   
}

but not show how i can move collection in class level and it maintain its type.

Need just hint on right direction.

1 Answers

What you want is to make your class generic and then constrain you class method to use that generic type.

class DynamicArray<T> {
    add(value:T):Array<T> {
        let collection = new Array<T>()        
        collection.push(value)
        return collection
    }   
}

When using the class you specify what type it will hold

const array = new DynamicArray<string>();
array.add('foo');
array.add(12); // will fail

The only way I can think of having a generic entry point would be a static class which instantiate a generic typed class.

class TypedArray<T> {
    private items: T[] = [];

    add(value: T): this {
        this.items.push(value);

        return this;
    }
}

class DynamicArray {
    static add<T>(value:T): TypedArray<T> {
        let collection = new TypedArray<T>()        
        collection.add(value);

        return collection
    }   
}

const array = DynamicArray.add('foo');
array.add('bar');
array.add(12); // fails
Related