facebook / facebook/flow

Feature request: Support string literal types for template literal tag functions

Open
#6,996 0 comments 1 reaction 0 assignees View on GitHub
feature request
Dominant language
Rust
Stars
22.3k
Forks
1.9k
PR merge metrics
No merged PRs in 30d

Description

A tagged template literal is basically a function whose first argument is an array of strings. When calling a regular function with an array of strings, it's possible to use type inference based on the literal contents of that array, but it's not possible with a tagged template literal.

Basically, I want to create a function that, when used as a template literal tag, returns a different type depending on the string you pass into it. This would be possible if a tagged template literal behaved the same way as a function that accepts an array of strings, as shown below.

I'm going to work on opening a PR for this, but wanted to open an issue to see what people think!

```
type Shape = {
'key1': string,
'key2': number
}

let x: Shape;

function argIsALiteral(arg: [T]): $ElementType {
return x[arg[0]];
}

// All good with a single item array
const res1 = argIsALiteral(['key1']); // infers string
const res2 = argIsALiteral(['key2']); // infers number

// Doesn't work with tagged template literal
const res3 = argIsALiteral`key1`; // flow error
```

Here's a link on try: https://flow.org/try/#0C4TwDgpgBAygFgQ0lAvFA3gKClA5AawhAEZcAuKAZ2ACcBLAOwHMAabPQkAJnKgYFcAtgCMINTAF9MmADYRgUAB4V4SCAG5pAM34MAxsDoB7BlAQ0mASUoBBADJ1gYhDIA8AFQrV6zAHwAKcyYKAG13AF0ASgoAEgBROUEIBmB3cAhXVUgWKHdfDHYaeX4aU0UQoJCABnDwzSlMAHpGqBsZGSgmIyMAEygAd0c4MypGJjkoRwhBMxoaBBBMPRNqKCLKYlRZq1sHJ3mZfxCCIlIo9ShmyYYtMUoqWjGllYV1ri2g63spg6OT7lw50uLUYtxo9wEIjE0iuABEjBBKAxcAp+kYaPgBkMoMAEEwmBA+k5BGAZAgnFAZD8XM8GKt1gBmD4WL57ZwyAAGnGIHPUQA

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.