简体   繁体   中英

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.

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:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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