typescript 获取泛型参数的类型

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18215899/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-11 01:08:02  来源:igfitidea点击:

Get type of generic parameter

genericstypestypescript

提问by Matěj Pokorny

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?

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

回答by Jeffery Grajkowski

typeofis 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.

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

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.

这是有效的,因为我操作的是 Holder 内部的值,而不是 Holder 本身。