Reputation: 849
If have some troble, i have array with function, like:
this._array = [handler, func, type]
How i need declare this private Property:
1. Array<any>
2. any[]
3. T[]
4. Array<T>
What difference in this declaration?
And some question:
this._array.push(()=>{ console.log("hey")})
How i can define type function?
Upvotes: 1
Views: 2113
Reputation: 4149
You can use a tuple instead of an array, eg.:
private _array: [any, () => void, string];
Upvotes: 0
Reputation: 68635
In you case if you don't know which types can be in your array use any[]
, which is not desired. I suggest you to refactor your code to have arrays with the same types.
1) Array<any>
- accept anything.
2) any[]
- is the same as above one.
console.log([].constructor);
console.log((new Array()).constructor);
3) T[]
contains only elements which type is T
. Can be used in Generic
4) Array<T>
same as the above.
Saying you have a class
class SomeClass<T> {
items: Array<T>;
}
const numbers = new SomeClass<number>();
const strings = new SomeClass<string>();
For numbers the items will be of type number[]
, for strings it will be string[]
. The type which will replace T
is got from the <T>
in the object creation statement.
Upvotes: 2
Reputation: 249466
Array<any>
and any[]
are equivalent and are arrays of anything (not type checking on items, best avoid these if you can help it)T[]
and Array<T>
are equivalent and are arrays of the given type T
, so you will get compile type checking for these.If you need to store something like [handler, func, type]
:
let arrary: Array<(param:number) => void> = []
With this version the items pushed are checked to conform to your handler signature.
Upvotes: 0
Reputation: 3233
TypeScript, like JavaScript, allows you to work with arrays of values. Array types can be written in one of two ways. In the first, you use the type of the elements followed by []
to denote an array of that element type:
let list: number[] = [1, 2, 3];
The second way uses a generic array type, Array<elemType>:
let list: Array<number> = [1, 2, 3];
More refer here : https://www.typescriptlang.org/docs/handbook/basic-types.html
Upvotes: 0