dee*_*our 8 javascript typescript lodash
我正在使用MomentTimezone在浏览器中进行时间操作。
我也使用TypeScript和Lodash。
我accountTimezone在window包含通过身份验证的用户的首选时区上有一些设置。我正在尝试创建一个辅助方法localMoment(),该方法将接受的许多签名中的moment.tz()任何一个,并将其附加window.accountTimezone为最终timezone: string参数。
似乎partialRight是我在寻找什么。
const localMoment = partialRight(moment.tz, window.accountTimezone);
Run Code Online (Sandbox Code Playgroud)
我遇到的问题与lodash文档中的此注释有关:
注意:此方法不会设置部分应用的函数的“长度”属性。
具体来说,对于像这样的调用localMoment('2019-08-01 12:00:00'),TypeScript抱怨localMoment()提供了1个参数,但期望为零。
如何避免TypeScript高兴地理解localMoment()应该moment.tz()通过MomentTimzone接口调用的调用,同时又避免了因使用而造成的混淆partialRight()?
我考虑过使用这种方法作为替代方法,但不知道如何键入...args以保持TypeScript满意。
const localMoment = (...args): Moment => moment.tz(...args, window.accountTimezone);
Run Code Online (Sandbox Code Playgroud)
没有干净的方法可以做到这一点。您要么必须选择退出输入,要么重新声明您自己的接口。
Typescript 本身无法做到这一点,只能选择声明一堆不同签名的“足够好”解决方案: https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/lodash/common/function。 d.ts#L1147
即使您以某种方式设法操纵打字稿界面,我怀疑您是否可以处理没有时区参数的
其他方法( zone、add、 ...):https: //github.com/DefinitelyTyped/DefinitelyTyped/blob/主/类型/时刻时区/时刻时区.d.ts#L20link
您可以实现的最好效果是避免使用实用程序类型复制整个界面Pick:
type CurriedMomentTimezone = Pick<moment.MomentTimezone, 'zone' | 'add' | 'link' | 'load' | 'names' | 'guess' | 'setDefault'> & {
(): moment.Moment;
(date: number): moment.Moment;
(date: number[]): moment.Moment;
(date: string): moment.Moment;
(date: string, format: moment.MomentFormatSpecification): moment.Moment;
(date: string, format: moment.MomentFormatSpecification, strict: boolean): moment.Moment;
(date: string, format: moment.MomentFormatSpecification, language: string): moment.Moment;
(date: string, format: moment.MomentFormatSpecification, language: string, strict: boolean): moment.Moment;
(date: Date): moment.Moment;
(date: moment.Moment): moment.Moment;
(date: any): moment.Moment;
}
localMoment = _.partialRight(moment.tz, this.accountTimezone) as CurriedMomentTimezone;
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
186 次 |
| 最近记录: |