Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Cannot define a matching template literal type to a defined template literal #43143

Closed
EdwardDrapkin opened this issue Mar 8, 2021 · 3 comments Β· Fixed by #43376
Closed

Cannot define a matching template literal type to a defined template literal #43143

EdwardDrapkin opened this issue Mar 8, 2021 · 3 comments Β· Fixed by #43376
Assignees
Labels
Bug A bug in TypeScript Fix Available A PR has been opened for this issue

Comments

@EdwardDrapkin
Copy link

Bug Report

πŸ”Ž Search Terms

string, template, literal, type

πŸ•— Version & Regression Information

This is the behavior in every version I tried, including Nightly

⏯ Playground Link

Playground link with relevant code

πŸ’» Code

function getCardTitle(title: string): `test-${string}` {
    return `test-${title}`;
}

πŸ™ Actual behavior

TS infers the type string for the returned string, instead of the templated type.

πŸ™‚ Expected behavior

No error!

@EdwardDrapkin EdwardDrapkin changed the title Cannot define a matching template literal type to a template literal in a function declaration Cannot define a matching template literal type to a defined template literal Mar 8, 2021
@EdwardDrapkin
Copy link
Author

It appears to happen in any case where there's a literal type, even the most trivial case fails:

const aString: `a${string}` = `a${'string'}`;

@RyanCavanaugh RyanCavanaugh added the Bug A bug in TypeScript label Mar 8, 2021
@RyanCavanaugh RyanCavanaugh added this to the TypeScript 4.3.1 milestone Mar 8, 2021
@RyanCavanaugh
Copy link
Member

as const shouldn't be needed here

@ahejlsberg
Copy link
Member

We currently only produce template literal types from template literal expressions in as const contexts. We tried template literal types for all template literal expressions in #41891, but reverted it because it was too breaky. However, a happy medium would be to give template literal types to expressions that are contextually typed by string-like types. I can't imagine that breaking anything and it would solve this and other related issues.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Bug A bug in TypeScript Fix Available A PR has been opened for this issue
Projects
None yet
Development

Successfully merging a pull request may close this issue.

6 participants