获取通用参数的类型 [英] Get type of generic parameter

查看:117
本文介绍了获取通用参数的类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

 函数evaluate(变量:any,type:string):any {
switch(type)
{
case'string':return String(variable);
case'number':return isNumber(variable)?数字(可变):-1;
case'boolean':{
if(typeof variable ==='boolean')
返回变量; ($)
$ b $ if(typeof variable ==='string')
return(< string> variable).toLowerCase()==='true';

if(typeof variable ==='number')
返回变量!== 0;

返回false;
}
default:return null;



函数isNumber(n:any):boolean {
return!isNaN(parseFloat(n))&& isFinite的(N);
}

我尝试使用泛型,但不知道如何从类型泛型参数。这是可能的吗?

是一个JavaScript运算符。它可以在运行时用于获取JavaScript知道的类型。泛型是一种TypeScript概念,它有助于检查代码的正确性,但在编译后的输出中不存在。所以简短的答案是否定的,这是不可能的。



但你可以这样做:

 类Holder< T> {
value:T;
构造函数(value:T){
this.value = value;
}
typeof():string {
返回typeof this.value;
}
}

试一试



这样做很有效,因为我使用的是Holder中的值,而不是Holder本身。 p>

I wrote 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 same with generics, but don't know how to get type from generic parameter. It´s possible?

解决方案

typeof is a JavaScript operator. It can be used at run time to get the types JavaScript knows about. Generics are a TypeScript concept that helps check the correctness of your code but doesn't exist in the compiled output. So the short answer is no, it's not possible.

But you could do something like this:

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

Try it out.

This works because I'm operating on the value inside Holder, not on the Holder itself.

这篇关于获取通用参数的类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆