gpt4 book ai didi

typescript - typescript 签名中的函数获取 setter

转载 作者:搜寻专家 更新时间:2023-10-30 21:44:55 25 4
gpt4 key购买 nike

我想创建一个类似 jQuery/d3 的 API,其中所有代码都可以很好地链接起来。

例如。

    // set the volume property
const foo = new OHLC().volume(func)

// get the volume property
const axis = new OHLC().volume()

如何重载方法以便识别返回类型

到目前为止,这是我的代码:

export class OHLC {
private _volume = (d: OHLCDatum) => d.volume

volume(fn?: (d: OHLCDatum) => number) {
if (!arguments.length) return this._volume;
this.volume = fn;
return this;
}
}

问题是当我分配 const axis = new OHLC().volume(func) 返回一个联合类型而不是我期望的 function 类型。

最佳答案

你要找的确实叫"overloading"它通过为同一功能提供多个(兼容的)签名来工作。然后,调用者使用与他们调用函数的方式相匹配的签名。

因此,首先我们提供您在用例中概述的 2 个签名:

volume(): (d: OHLCDatum) => number;
volume(fn: (d: OHLCDatum) => number): OHLC;

随后是带有所有 重载签名兼容的签名的实现。即捕获调用者使用任何重载的效果的签名。

volume(fn?: (d: OHLCDatum) => number): OHLC | ((d: OHLCDatum) => number) {
if (fn == null) return this._volume;
this._volume = fn;
return this;
}

我已将 if (!arguments.length) 更改为 if (fn == null) 哪个 typescript 更擅长缩小 this。 _volume = fn 赋值。

Playground code example

为了支持这种格式的多个属性,我们可以将逻辑包装到一个具有关联接口(interface)的函数中,该接口(interface)使用相同的重载签名。

interface FluentProperty<C, V> {
(): V;
(val: V): C;
(val?: V): C | V;
}

然后创建用于创建新属性的助手。这在创建过程中缺乏一些类型安全,因为 keyof OHLC 将不包含任何私有(private)属性,但类与以前一样类型安全。

function mkOHLCProperty<V>(key: string): FluentProperty<OHLC, V> {
return function property(this: OHLC, val?: V): OHLC | V {
if (val == null) return (this as any)[key];
(this as any)[key] = val;
return this;
} as FluentProperty<OHLC, V>
}

最后创建私有(private)字段和相关属性:

class OHLC {
private _volume = (d: OHLCDatum) => d.volume
volume = mkOHLCProperty<OHLC['_volume']>('_volume')
}

Playground code example

关于typescript - typescript 签名中的函数获取 setter ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57237622/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com