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

Const contexts for template literals #40707

Merged
merged 3 commits into from
Sep 22, 2020
Merged

Conversation

ahejlsberg
Copy link
Member

With this PR we produce template literal types for template literal expressions in const assertions.

const tc1 = 'foo' as const;  // 'foo'
const tc2 = 'bar' as const;  // 'bar'
const tc3 = `${tc1}-${tc2}` as const;  // 'foo-bar'
const tc4 = [`${tc1}-${tc2}`, `${tc2}-${tc1}`] as const;  // readonly ['foo-bar', 'bar-foo']

function test<T extends string, U extends string>(x: T, y: U) {
    return `${x}-${y}` as const;  // `${T}-${U}`
}

const ts1 = test('foo', 'bar');  // 'foo-bar'
const ts2 = test('foo', !!true ? '0' : '1');  // 'foo-0' | 'foo-1'
const ts3 = test(!!true ? 'top' : 'bottom', !!true ? 'left' : 'right');  // 'top-left' | 'top-right' | 'bottom-left' | 'bottom-right'

The type of a template literal `aaa${x}bbb${y}ccc` in a const context is `aaa${X}bbb${Y}ccc`, where X and Y are the types of x and y respectively, or string when x or y is not assignable to string | number | boolean | bigint. Template literal types resulting from template literals in const contexts are normalized as described in #40336, meaning that a resulting type may actually be a union of literal types.

@typescript-bot typescript-bot added the For Uncommitted Bug PR for untriaged, rejected, closed or missing bug label Sep 22, 2020
@ahejlsberg ahejlsberg added this to the TypeScript 4.1.0 milestone Sep 22, 2020
@ahejlsberg ahejlsberg merged commit 5d6cce5 into master Sep 22, 2020
@ahejlsberg ahejlsberg deleted the templateLiteralsAsConst branch September 22, 2020 23:11
@Roaders
Copy link

Roaders commented Sep 23, 2020

Very nice!

@lizraeli
Copy link

This is incredible!

@Roaders
Copy link

Roaders commented Sep 24, 2020

So why isn't this available on the nightly build on playground yet?
If I select nightly it loads 4.1.0-dev.20200921 but I can see 4.1.0-dev.20200923 on npmjs (tagged as next).

When I try to load 4.1.0-dev.20200923 into playground it fails... 😢

@weswigham
Copy link
Member

Last night's (and I think the day before, too, maybe) nightly publish failed due to a tooling issue - there should be a new nightly in a few hours.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
For Uncommitted Bug PR for untriaged, rejected, closed or missing bug
Projects
None yet
Development

Successfully merging this pull request may close these issues.

5 participants