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

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 + "https://stackoverflow.com/" + 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!

Leave a Comment