2

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 Answer 1

4

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
Sign up to request clarification or add additional context in comments.

4 Comments

Yes you are right but point is i dont want to set type, It should be some how set auto automatic const array = new DynamicArray(); array.add('foo'); array.add(12); // will fail
Your example is fundamentally wrong, it returns an array which you don't use. Correct usage would be array.add('foo').push(12); // which will fail. If you'd look what's in array after both of your add() you'd see that it's an empty object
Yes @opex i know that but example is not perfect but i just put it to show what i mean. I could not found any solution to this issue as well. your example is same as we add type an array. what we are looking right now is some kind of lat init of collection
You cannot change the type of a variable after it's been created. array is of type DynamicArray which contains a method to add values of arbitrary type. That will not change just because you call add() on array, it will still have the type DynamicArray

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.