'Modified Template Literal Types
const lines = ['one', 'two', 'three'] as const;
const linesWithA = lines.map(line => `${line}-A` as const);
const linesWithB = lines.map(line => `${line.toUpperCase()}-B` as const);
will give types:
declare const lines: readonly ["one", "two", "three"];
declare const linesWithA: ("one-A" | "two-A" | "three-A")[];
declare const linesWithB: `${string}-B`[];
Is it somehow possible to get a type for linesWithB as ("ONE-B" | "TWO-B" | "THREE-B")[]? I'm getting `${string}-A`[] instead, becaue of the toUpperCase call.
Solution 1:[1]
The problem is that the toUpperCase just returns a string:
const test1 = 'no uppercase'.toUpperCase();
// const test1: string
I think the safest way to handle this issue is to create a new function toUpperCase with an assertion to get the proper type:
const toUpperCase = <S extends string>(line: S) =>
line.toUpperCase() as Uppercase<S>
const test2 = toUpperCase('uppercase');
// const test2: "UPPERCASE"
If you use this function in linesWithB, it will have the desired return type:
const linesWithB = lines.map(line => `${toUpperCase(line)}-B` as const);
// const linesWithB: ("ONE-B" | "TWO-B" | "THREE-B")[]
Update: There's a TypeScript issue about this, but it will (probably?) require making String generic, which is a rather extensive change.
Solution 2:[2]
I can only do it with a (fairly innocuous) type assertion:
const lines = ['one', 'two', 'three'] as const;
type Lines = typeof lines;
type UpperLines = Uppercase<Lines[number]>[];
const linesWithA = lines.map(line => `${line}-A` as const);
const linesWithB = (lines.map(line => line.toUpperCase()) as UpperLines).map(line => `${line}-B` as const);
It's also possible without the intermediary type aliases, but...I wouldn't:
const lines = ['one', 'two', 'three'] as const;
const linesWithA = lines.map(line => `${line}-A` as const);
const linesWithB = (lines.map(line => line.toUpperCase()) as [Uppercase<(typeof lines)[number]>]).map(line => `${line}-B` as const);
Hopefully someone better at TypeScript than I can do it without the type assertion, though again, it's fairly innocuous.
Solution 3:[3]
You could augment the global namespace and add an overload for the toUpperCase function:
declare global {
interface String {
toUpperCase<T extends string>(this: T): Uppercase<T>
}
}
No type assertion is required:
// ("ONE-B" | "TWO-B" | "THREE-B")[]
const linesWithB = lines.map(line => `${line.toUpperCase()}-B` as const)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | |
| Solution 3 | cherryblossom |
