Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
5
rated 0 times [  6] [ 1]  / answers: 1 / hits: 15522  / 5 Years ago, wed, january 23, 2019, 12:00:00

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


More From » string

 Answers
44

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!


[#52726] Friday, January 18, 2019, 5 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
randall

Total Points: 492
Total Questions: 99
Total Answers: 103

Location: Solomon Islands
Member since Fri, Oct 8, 2021
3 Years ago
;