zimex
zimex

Reputation: 873

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

Upvotes: 1

Views: 136

Answers (1)

J&#243;zef Podlecki
J&#243;zef Podlecki

Reputation: 11283

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.

Upvotes: 1

Related Questions