簡體   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