TypeScript:获取泛型类型的类型

5
我是一名C#程序员,刚开始接触TypeScript,并且在特殊的泛型实现方面遇到了困难。
以下是我的代码:
function createValue<TValue extends string | boolean>(): TValue[]
{
    let result = new Array<TValue>();

    if (typeof TValue === "string") // error 'TValue' only refers to a type, but is being used as a value here
    {
        result[0] = "abc" as TValue;
    }
    else
    {
        result[0] = false as TValue;
    }

    return result;
}

console.log(createValue<boolean>());

我如何获取类型?

我已经尝试了非常丑陋的解决方案来创建一个值,但它也没有像预期的那样表现。

let value : TValue = new Array<TValue>(1)[0];
let type = typeof value; // undefined

对象类型有多种解决方案,但对于原始类型我还不清楚。

您能帮我吗?

谢谢。


这个回答解决了你的问题吗?获取泛型参数的类型 - bmtheo
很遗憾,因为最佳解决方案需要一个已存在、定义好的值——而我没有这个值。是否有一种动态创建定义好的基本类型的解决方案? - porti20
恐怕不行,这就是他们在链接答案中解释的内容:“泛型是 TypeScript 的一个概念,它有助于检查代码的正确性,但不会存在于编译输出中。因此,简短的答案是不行。” - bmtheo
类型在运行时不存在。 - Aleksey L.
2个回答

1
因为类型在运行时不存在,所以我得到了这样的解决方案:
enum Types
{
    string,
    boolean,
    number
}

function getType<TValue extends Types.string | Types.boolean>(t: TValue): Array<TValue extends Types.string ? string : boolean>
{
    if (<Types>t == Types.string)
    {
        let arr = new Array<string>();
        arr[0] = "abcd";
        return arr as Array<TValue extends Types.string ? string : boolean>;       
    }

    let arr = new Array<boolean>();
    arr[0] = false;
    return arr as Array<TValue extends Types.string ? string : boolean>;     
}

console.log(getType(Types.boolean));

0

你的问题在于在运行时使用了 TypeScript 类型。TypeScript 被编译成 JavaScript,因此你的执行过程根本不会看到类型 TValue

typeof 运算符用于在其他地方重用类型信息,但不是在运行时。例如:

function test(arg: string): boolean;

function test2(func1: typeof test): boolean;

根据您想要实现的目标,您需要提供一个字符串参数来指定您的操作。
function createValue(type: 'string' | 'boolean') {
    let result = new Array();

    if (type === "string") 
    {
        result[0] = "abc";
    }
    else
    {
        result[0] = false;
    }

    return result;
}

console.log(createValue('boolean'));

TypeScript 应该能够从那里推断出你的类型。如果不能,你可以看一下 条件类型


条件类型对我来说很关键,感谢您的解释。 - porti20

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接