简体   繁体   English

Typescript:是否可以将泛型类型评估为字符串文字?

[英]Typescript: Is it possible to evaluate generic type into string literal?

Is it possible to evaluate generic type into a string literal without being explicit?是否可以在不明确的情况下将泛型类型评估为字符串文字?

Here is an example what I have in mind:这是我想到的一个例子:

function foo<T>(type: T): { type: T } {
    return { type };
}

// type is { type: string } I would like it to be { type: 'FooBar' } without being explicit
const bar = foo('FooBar'); 

// is it possible not to do this and get same result?
const fooBar = foo<'FooBar'>('FooBar'); 
const barFoo = foo('FooBar' as const);

Playground Link 游乐场链接

I am also bit surprised Literal Narrowing doesnt propagate to foo function and instead it defaults to string type.我也有点惊讶Literal Narrowing不会传播到foo function 而是默认为string类型。

const test = 'FooBar';
const barFoo = foo(test);

However, when I explicity specify type there is no problem.但是,当我明确指定类型时,没有问题。

const test: 'FooBar' = 'FooBar';
const barFoo = foo(test);

Well this is where we started.好吧,这就是我们开始的地方。

With a little bit of fiddling in foo function:稍微摆弄一下foo function:

function foo<T extends string>(type: T): { type: T } {
    return { type };
}

const test = 'FooBar';
const barFoo = foo(test);

I was looking at intellisense result when I peeked at expression and it now propagates the type.当我查看表达式时,我正在查看智能感知结果,它现在传播了类型。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM