Reputation: 7337
I have a variable a
declared with type string
, but uninitialised. Is there a way to get the string
type instead of an undefined
?
> let a:string;
undefined
> console.log(typeof a);
undefined
Upvotes: 0
Views: 248
Reputation: 7337
As there is no way to get the type at runtime; and based on @deceze's comment (save the metadata separately)
In case it helps someone this workaround does the job. It does not use Reflect decorators
> class C {
constructor(
public var1?:string,
public var2?:string,
public var3?:number
) {}
typeof(v) {
switch (v) {
case 'var1':
case 'var2':
return 'string';
case 'var3':
return 'number';
}
}
}
> let c = new C();
> console.log(Object.keys(c).map(
a => {
console.log( ' Var: ' + a +
' - Type: ' + c.typeof(`${a}`) )
})
);
Var: var1 - Type: string
Var: var2 - Type: string
Var: var3 - Type: number
[ undefined, undefined, undefined ]
Upvotes: 0
Reputation: 12021
yes, there is a way to get types metadata in typescript, but you would have to activate reflect metadata option in typescript compiler config and import reflect metadata polyfill, which will increase you bundle size.
look here to find more suitable example of accessing typescript types.
Upvotes: 2