首先,让我明确一下,我想要的不是联合类型,而是简单的字符串拼接,即 "Hel" + "lo" = "Hello"
,但是针对字符串字面量类型。
实际上,我有一个函数,它接受两个字符串字面量作为参数,一个是 namespace
,一个是 name
,并以它们之间用 / 连接后的字符串作为输出,但是我无法找到一种方法将输出设置为字符串字面量而不是普通字符串。
我需要它成为一个字符串字面量,因为输出将被用作对象的键。
我尝试过类型交叉(&
)、+
、.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
是一个通用的 字符串
,但我想要它成为一个 字符串字面量
"admin/home"