【问题标题】:Callable typescript interface is not callable?可调用的打字稿接口不可调用?
【发布时间】:2019-05-02 04:27:55
【问题描述】:

我正在尝试编写ts-optchain 的集合版本。该功能将尝试返回具有拼接更改的根对象的副本。这样原件不会以任何方式更改或修改。然而,对于尚未修改的对象区域,它们会作为引用复制到浅复制操作中(通过Object.assign(...))。

我要验证的测试如下:

const example = { a: { b: { c: { d: 5 } } } };
const out = osc(example).a.b.c.d(6);
expect(out).to.be.deep.eq({ a: { b: { c: { d: 6 } } } });

...其中osc(可选设置链)是我模仿opt-chainoc 函数的函数。

我希望结果与Object.assign({}, example, {a: Object.assign({}, example.a, {b: Object.assign({}, example.a.b, {c: Object.assign({}, example.a.b.c, {d: 6})})})}); 有点相似

上面的方法写、读和维护都很痛苦。因此,制作此功能的理由。

实现

我的尝试如下:

// ----- Types -----
// Generic type "R" -> The returned root object type when setting a value
// Generic type "T" -> The type for the proxy object
interface TSOSCDataSetter<R, T> {
  (value: Readonly<T>): Readonly<R>;
}

type TSOSCObjectWrapper<R, T> = { [K in keyof T]-?: TSOSCType<R, T[K]> };

interface TSOSCArrayWrapper<R, T> {
  length: TSOSCType<R, number>;

  [K: number]: TSOSCType<R, T>;
}

interface TSOSCAny<R> extends TSOSCDataSetter<R, any> {
  [K: string]: TSOSCAny<R>; // Enable deep traversal of arbitrary props
}

type TSOSCDataWrapper<R, T> =
  0 extends (1 & T) // Is T any? (https://stackoverflow.com/questions/49927523/disallow-call-with-any/49928360#49928360)
    ? TSOSCAny<R>
    : T extends any[] // Is T array-like?
    ? TSOSCArrayWrapper<R, T[number]>
    : T extends object // Is T object-like?
      ? TSOSCObjectWrapper<R, T>
      : TSOSCDataSetter<R, T>;

export type TSOSCType<R, T> = TSOSCDataSetter<R, T> & TSOSCDataWrapper<R, T>;

// ----- Helper functions -----
function setter<K extends keyof V, V>(original: () => (Readonly<V> | undefined), key: K, value: Readonly<V[K]>): Readonly<V> {
  // Shallow copies this layer with the spliced in value specified. Works with both dictionaries and lists.
  return Object.assign(typeof key === "string" ? {} : [], original(), { [key]: value });
}

function getter<K extends keyof V, V>(object: Readonly<V> | undefined, key: K): Readonly<V[K]> | undefined {
  // Assists in optionally fetching down a continuous recursive chain of index-able objects (dictionaries & lists)
  return object === undefined ? object : object[key];
}

// ----- Internal recursive optional set chain function -----
function _osc<R, K extends keyof V, V>(root: Readonly<R> | undefined, get_chain: () => (Readonly<V> | undefined), set_chain: (v: Readonly<V>) => Readonly<R>): TSOSCType<R, V> {
  // `root` is passed in as an argument and never used. This is just to maintain the typing for <R>.
  // `get_chain` is a constructed recursive function that will return what the value of this object is at this node.
  // `set_chain` is a constructed recursive function that will assist in building and splicing in the specified value.

  return new Proxy(
    {} as TSOSCType<R, V>, // Blank object. I don't use `target`.
    {
      get: function (target, key: K): TSOSCType<R, V[K]> {
        const new_get_chain = (): (Readonly<V[K]> | undefined) => getter(get_chain(), key);
        const new_set_chain = (v: Readonly<V[K]>): Readonly<R> => set_chain(setter(get_chain, key, v));
        return _osc(root, new_get_chain, new_set_chain);
      },
      apply: function (target, thisArg, args: [Readonly<V>]): Readonly<R> {
        return set_chain(args[0]);
      }
    }
  );
}

// ----- Exposed optional set chain function -----
export function osc<R, K extends keyof R>(root: Readonly<R> | undefined): TSOSCType<R, R> {
  const set_chain = (value: Readonly<R>): Readonly<R> => value;
  return _osc(root, () => root, set_chain);
}

问题

很遗憾,我收到错误消息:osc(...).a.b.c.d is not a function。这就是我的困惑开始的地方。从osc(和_osc)函数返回的是TSOSCType类型,它扩展了接口TSOSCDataSetter。接口TSOSCDataSetter 指定继承该接口的对象本身是可调用的:

interface TSOSCDataSetter<R, T> {
  (value: Readonly<T>): Readonly<R>;
}

osc_osc 调回的是Proxy 类型TSOSCType(很像ts-optchain)。此代理对象有助于构建链并键入完成对象链。但更重要的是对于这个问题,实现了apply方法:

apply: function (target, thisArg, args: [Readonly<V>]): Readonly<R> {
  return set_chain(args[0]);
}

那么为什么TSOSCType 类型不可调用?

【问题讨论】:

    标签: typescript


    【解决方案1】:

    发生这种情况的原因是因为只能调用函数周围的代理(并设置apply 陷阱)。你的 {} as TSOSCType&lt;R, V&gt; 演员掩盖了你正在做的事情在运行时是不可能的事实,并指示 TypeScript 信任你(错误地)。

    将该语句更改为 function(){} as unknown as TSOSCType&lt;R, V&gt; 使其按预期工作。

    See this in the Playground.

    作为一般经验法则,每当您在使用 TypeScript 时遇到运行时 TypeError,这意味着 TypeScript 信任您并且您背叛了它。这几乎总是意味着演员。当您遇到此类错误时,您的演员应该是直接的嫌疑人。

    【讨论】:

    • “TypeScript 信任你,而你却背叛了它”——为什么我会感到如此内疚? :D
    • @Yatrix 因为你可能是。 ಠ_ಠ
    猜你喜欢
    • 2018-02-27
    • 1970-01-01
    • 2014-07-12
    • 2019-06-12
    • 2021-02-21
    • 2020-07-09
    • 2017-04-15
    • 2018-12-09
    • 2019-03-14
    相关资源
    最近更新 更多