简体   繁体   English

在打字稿中将动态类型定义为数组

[英]Define Dynamic type to array in typescript

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.只需要提示正确的方向。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM