Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there currently anyway to concatenate two or more string literal types to a single string literal type in TypeScript right now?

First of all, let me make it clear that what I'm looking isn't a union type but a straight up concatenation i.e "Hel" + "lo" = "Hello" but for string literal types

Essentially I have a function which takes two string literals, a namespace and a name, and combines these with a / in between as it's output, but I can't figure out a way to make the output a string literal and not a generic string.

I need it to be a string literal because the output will be used as a key of an object.

I've tried type intersections(&), +, .concat()

function makeKey<NS extends string, N extends string>(namespace: NS, name: N) {
    return namespace + '/' + name; // <- want this to be `NS + / + N` = `NS/N`
}
// I want this to return a string literal rather than a generic string

const objKey = makeKey('admin', 'home')
// I want typeof objKey to be a string literal: `"admin/home"`, not a generic `string`

typeof objKey is a generic string but I want it to be a string literal "admin/home"

like image 401
Dudeonyx Avatar asked Jan 23 '19 19:01

Dudeonyx


People also ask

Can we concatenate two strings?

You concatenate strings by using the + operator. For string literals and string constants, concatenation occurs at compile time; no run-time concatenation occurs. For string variables, concatenation occurs only at run time.

How do I concatenate two variables in TypeScript?

TypeScript | String concat() Method The concat() is an inbuilt function in TypeScript which is used to add two or more strings and returns a new single string. Syntax: string. concat(string2, string3[, ..., stringN]);

What are string literal types in TypeScript?

The string literal type allows you to specify a set of possible string values for a variable, only those string values can be assigned to a variable. TypeScript throws a compile-time error if one tries to assign a value to the variable that isn't defined by the string literal type.

How many types of string literals are there?

There are three sets of literal types available in TypeScript today: strings, numbers, and booleans; by using literal types you can allow an exact value which a string, number, or boolean must have.


2 Answers

TS4.1+ answer:

You can now use template literal types to do this:

function makeKey<NS extends string, N extends string>(namespace: NS, name: N) {     return namespace + '/' + name as `${NS}/${N}` }  const objKey = makeKey('admin', 'home'); // const objKey: "admin/home" 

Playground link


Pre TS4.1 answer:

The answer is unfortunately no. There are several feature suggestions filed in GitHub that, if implemented, might give you such functionality (microsoft/TypeScript#12754 to augment keys during mapped types, or microsoft/TypeScript#6579 to manipulate string types via regular expressions) but I don't think they are being actively worked on. I don't see anything in the roadmap about it, anyway. If you really want to see this happen, you might want to go to one of those GitHub issues and give them a 👍 or describe your use case if it's particularly compelling. But I wouldn't hold my breath. Sorry!

like image 184
jcalz Avatar answered Sep 22 '22 03:09

jcalz


It will be possible once Template string types will be released (looks like in typescript 4.1):

function makeKey<NS extends string, N extends string>(namespace: NS, name: N) {
    return (namespace + '/' + name) as `${NS}/${N}`;
}

const objKey = makeKey('admin', 'home') // objKey is of type 'admin/home'

Playground


Template string types are the type space equivalent of template string expressions. Similar to template string expressions, template string types are enclosed in backtick delimiters and can contain placeholders of the form ${T}, where T is a type that is assignable to string, number, boolean, or bigint. Template string types provide the ability to concatenate literal strings, convert literals of non-string primitive types to their string representation, and change the capitalization or casing of string literals. Furthermore, through type inference, template string types provide a simple form of string pattern matching and decomposition.

Some examples:

type EventName<T extends string> = `${T}Changed`;
type Concat<S1 extends string, S2 extends string> = `${S1}${S2}`;
type T0 = EventName<'foo'>;  // 'fooChanged'
type T1 = EventName<'foo' | 'bar' | 'baz'>;  // 'fooChanged' | 'barChanged' | 'bazChanged'
type T2 = Concat<'Hello', 'World'>;  // 'HelloWorld'
type T3 = `${'top' | 'bottom'}-${'left' | 'right'}`;  // 'top-left' | 'top-right' | 'bottom-left' | 'bottom-right'

More details and examples here

like image 23
Aleksey L. Avatar answered Sep 23 '22 03:09

Aleksey L.