Typescript:获取泛型类型的类型

por*_*i20 5 generics typescript

我是 Typescript 的新手(来自 C#),并且正在努力解决“特殊”通用实现。

这是我的代码:

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>());
Run Code Online (Sandbox Code Playgroud)

我是如何得到类型的?

我已经尝试过相当丑陋的解决方案来创造价值,但这也没有达到预期的效果。

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

对于对象类型存在多种解决方案,但我没有得到基元的解决方案。

你能给我任何帮助吗?

谢谢

por*_*i20 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));
Run Code Online (Sandbox Code Playgroud)