繁体   English   中英

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

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

是否可以在不明确的情况下将泛型类型评估为字符串文字?

这是我想到的一个例子:

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);

游乐场链接

我也有点惊讶Literal Narrowing不会传播到foo function 而是默认为string类型。

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

但是,当我明确指定类型时,没有问题。

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

好吧,这就是我们开始的地方。

稍微摆弄一下foo function:

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

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

当我查看表达式时,我正在查看智能感知结果,它现在传播了类型。

暂无
暂无

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

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