创建一个计算结果为字符串并可以将其他字符串作为属性的构造

Create a construct that evaluates to a string and can have other strings as properties

我想制作特定的 JavaScript 构造,并使用适当的 TypeScript 打字

我希望我的构造:

  1. return 求值时的字符串
  2. 具有在评估时 return 不同字符串的属性

以类似于如何创建嵌套可调用函数的方式:

const fn = () => "foo"
fn.bar = () => "bar"

fn() // "foo"
fn.bar() // "bar"

类似

const foo = "foo";
foo.bar = "bar" // Unfortunately doesn't work

foo // "foo"
foo.bar // "bar" 

type Foo = "foo" & { bar: "bar" }

它也可以是 属性 绑定到父 Proxy 对象,如有必要。当我尝试使用代理实现它时,我 运行 遇到了无法区分浅层 (proxy.foo) 和深层 (proxy.foo.bar) 属性 访问的问题陷阱:

const proxy = new Proxy({}, { 
  get: (target, prop) => {
    // prop is "foo" for both `proxy.foo` and `proxy.foo.bar` accesses, 
    // presumably because they are two separate property access operations 
    // `proxy.foo.bar` = `(proxy.foo).bar`
  }
}

甚至可以在 JavaScript 中构建这样的结构吗?
可以在 TS 中输入吗?


编辑:描述我的用例

我希望创建一个架构,将我网站的语义部分映射到它们各自的 url:

const urlSchema = someMagic();

urlSchema.settings // `/settings`
urlSchema.settings.personal // `/settings/personal`

然后我想从整个应用程序导入此架构以创建链接等。

I want my construct to return a string when evaluated and have properties

那是不可能的。计算结果为字符串 returns 字符串值的表达式,字符串是原始值而不是可能具有属性的对象。代理在这里无济于事,因为代理始终也是一个对象。

另见 Extend primitives without prototyping them