Get general parameter type

I wrote a small function for better handling with types.

function evaluate(variable: any, type: string): any { switch (type) { case 'string': return String(variable); case 'number': return isNumber(variable) ? Number(variable) : -1; case 'boolean': { if (typeof variable === 'boolean') return variable; if (typeof variable === 'string') return (<string>variable).toLowerCase() === 'true'; if (typeof variable === 'number') return variable !== 0; return false; } default: return null; } } function isNumber(n: any): boolean { return !isNaN(parseFloat(n)) && isFinite(n); } 

I try the same with generics, but don’t know how to get the type from a generic parameter. Is it possible?

+6
source share
1 answer

typeof is a JavaScript statement. It can be used at runtime to find out what JavaScript knows about. Generics is a TypeScript concept that helps verify that the code is correct, but does not exist in compiled form. So the short answer is no, that’s not possible.

But you can do something like this:

 class Holder<T> { value: T; constructor(value: T) { this.value = value; } typeof(): string { return typeof this.value; } } 

Give it a try .

This works because I'm working on the value inside the Holder, and not on the holder itself.

+9
source

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


All Articles