【问题标题】:Create a construct that evaluates to a string and can have other strings as properties创建一个计算结果为字符串并且可以将其他字符串作为属性的构造
【发布时间】:2021-06-18 10:28:12
【问题描述】:

我想使用适当的 TypeScript 类型制作特定的 JavaScript 构造

我希望我的构造:

  1. 求值时返回一个字符串
  2. 具有在评估时返回不同字符串的属性

与创建嵌套可调用函数的方式类似:

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 对象的属性。当我尝试使用代理实现它时,我遇到了无法区分来自 get 陷阱的浅 (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`

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

【问题讨论】:

  • 你想使用这个构造的actual problem是什么?
  • @Bergi :嘿,我添加了编辑我的帖子以包含用例。感谢您的宝贵时间。
  • 不可能。但是您可以轻松地使urlSchema.settings 返回一个对象,当在String(urlSchema.settings) 中使用时,该对象的计算结果为字符串/settings

标签: javascript typescript proxy properties


【解决方案1】:

我希望我的构造在评估时返回一个字符串并具有属性

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

另见Extend primitives without prototyping them

【讨论】:

    猜你喜欢
    • 2017-12-19
    • 2014-03-04
    • 1970-01-01
    • 1970-01-01
    • 2012-08-31
    • 1970-01-01
    • 1970-01-01
    • 2013-07-24
    • 1970-01-01
    相关资源
    最近更新 更多