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

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

问题描述

为了更好地处理类型,我编写了小函数.

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 是一个 JavaScript 操作符.可以在运行时使用它来获取 JavaScript 知道的类型.泛型是一个 TypeScript 概念,可帮助检查代码的正确性,但在编译输出中不存在.所以简短的回答是否定的,这是不可能的.

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.

但你可以这样做:

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

试试看.

这是可行的,因为我操作的是 Holder 内部的值,而不是 Holder 本身.

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

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

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