Typescript equivalent? unknown pattern

Let's say I want to declare an array of generics in Typescript. What would be the equivalent of an unknown template? "in Java?

This compiles, but it seems a bit uncomfortable. MyGeneric<any>[];

I would like the declaration to be equivalent to Java MyGeneric<?>[]; , that is, an array of the same type, but the type is unknown when it is declared.

Greetings.

+5
source share
2 answers

I don't think Typescript has a later binding of generic types.

But if this particular code was in the context of a function, you could use generics to achieve a similar thing.

 function example<T>(val:T){ let a : T[] return [val] } let a = example(4) // number[] :: [4] let b = example('hello') // string[] :: ['hello'] 

Here is an interactive example: link

Try hovering over a or b to see it in action.

+1
source

Let's say I want to declare an array of generics in Typescript. What would be the equivalent of an unknown template? "in Java?

To have a string array

 var foo:string[]; 

This is the same as with TypeScript:

 var foo:Array<string>; 

If you need an array of something, just use any :

 var foo:any[] = ['asdf',123]; // Anything is allowed in this array. 
0
source

Source: https://habr.com/ru/post/1234129/


All Articles