Reputation: 10902
I'm reading up on generics in Typescript. Didn't even realize they were there:
var list: number[] = [1, 2, 3];
// Alternatively, using the generic array type
var list: Array<number> = [1, 2, 3];
Which made me curious whether if I said:
var list = [1,2,3]
Typescript would infer the type and if so, what type it would infer. So I am wondering whether there's a way for me to ask Typescript to show me the type of a variable.
Upvotes: 1
Views: 82
Reputation: 950
Check the Microsoft Visual Studio Code - it's a small editor, pretty useful for Typescript. Has the best support for Typescript. If you hover over variables it will tell you the type by itself.
Typescript compiler by default tries to help as much as possible, so if you're setting up the variable like :
let abc = 'ABC';
you don't have to specify the type (it will automagically detect that this is a string). For array generics it's bit more complex, it will loop through all keys in array pick every key type. for example you can have:
let test = ['test', 123];
And this array will get typed to Array<string|number>
The web tool is pretty useful for quick checking but if you work on bigger projects you won't copy&paste files into browser window. PHPStorm/WebStorm has pretty good TS support but sadly it won't tell you variable types - Microsoft Visual Studio Code will do.
And a nice thing about VisualStudioCode -> it free and written in Typescript ;)
Upvotes: 2
Reputation: 11740
This functionality is usually available through your development tool (opinions vary, but there are several available for free download). In many cases, including this one, you can be sure of the type by looking at what is being assigned (here, the type is number[]
, as you would expect).
If you're using a plain text editor while trying things out, you can paste your code into the "Playground" section of the TypeScript website - for example, here's your code, and by hovering over list
you can see that its type is number[]
.
Note that types are erased in typescript, so you cannot determine the type of generics at runtime, you have to pass in the constructor (since you're coding in Java, this should be familiar).
Upvotes: 1