首先,让我明确指出,我要寻找的不是联合类型,而是直接连接,即"Hel" + "lo" = "Hello"
,而是字符串文字类型
本质上,我有一个函数,它接受两个字符串文本,一个namespace
和一个name
,并将它们与a/in之间的字符组合作为输出,但我无法找到一种方法使输出成为字符串文本而不是一般字符串.
我需要它是字符串文字,因为输出将用作对象的键.
我试过输入交叉点(&
)、+
、.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
是通用string
,但我希望它是string literal
"admin/home"