【问题标题】:Function/helper to lookup self from object从对象中查找自我的函数/助手
【发布时间】:2022-11-01 23:02:26
【问题描述】:

用于值查找的 API 存在于集合中,这很有意义并且在绝大多数情况下都有效。好奇是否存在 API 以另一种方式:

const store = {key: 1}
const getKey = () => "key" as (string | undefined) // might be compute-heavy
const result = store[getKey()] // undefined cannot be used as an index type. Can't do this.

const result = getKey() && store[getKey()] // needed to call getKey() twice here, meaning I can't inline efficiently

const result = getKey()?.valueIn(store) // would be awesome if this returned 1
valueIn(store) {store[self]} // under the hood

【问题讨论】:

  • 只需使用一个额外的变量。甚至做一个函数。不要为了这样一个微不足道的功能而跳过箍。
  • this 这样的东西?我不确定你在问什么,但你真的应该关注 VLAZ 的评论和做这个。
  • 辅助函数可能很简单(我只是好奇是否已经存在内置的东西)。我添加了下面的助手作为示例。谢谢!

标签: typescript


【解决方案1】:

我想做一个助手很容易......

const maybeGet = (store, key) => key && store[key];

const result = maybeGet(store, getKey())

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-06-22
    • 1970-01-01
    • 2016-03-19
    • 2010-12-25
    • 2023-03-26
    • 1970-01-01
    • 2019-02-10
    相关资源
    最近更新 更多