gpt4 book ai didi

typescript - 在 TypeScript 中构建机会 Mixin

转载 作者:行者123 更新时间:2023-12-04 16:01:57 24 4
gpt4 key购买 nike

我正在研究 ChanceJS mixin我计划通过 npm 分发。

我在尝试定义正确的接口(interface)和类型时遇到问题。

包示例://index.ts

import * as Chance from 'chance';

export interface ITime {
time(): string;
}

function time() {
const h = chance.hour({ twentyfour: true });
const m = chance.minute();
return `${h}:${m}`;
};

export const time: ITime = {
time,
};

有人会如何消费它的示例:
import * as Chance from 'chance';
import { time } from 'chance-time';

const chance = new Chance();
chance.mixin(time);

chance.time()

我得到的错误是:
Error:(12, 14) TS2345: Argument of type 'ITime' is not assignable to parameter of type 'MixinDescriptor'.
Index signature is missing in type 'ITime'.
Error:(25, 26) TS2339: Property 'time' does not exist on type 'Chance'.

最佳答案

它看起来像 DefinitelyTyped definitions for ChanceJS并不真正支持你正在尝试做的事情。对此的理想解决方法是更改​​这些类型,但假设您不想这样做,类型断言将成为您的 friend 。

我没有安装 ChanceJS,因此您可能需要更改以下代码(命名空间等)才能使其正常工作:

const chance = new Chance() as Chance.Chance & ITime;
chance.mixin(time as any); // no error
chance.time(); // no error now I hope

在第一行,想法是 chance最终将成为 Chance和一个 ITime ,因为这就是 mixin 函数所做的。这将允许 chance.time()行编译没有错误。

在第二行中,您只是在抑制“缺少索引签名”错误。还有其他方法可以解决它,但要点是因为 ITime是没有索引签名的接口(interface),您不能将其分配给具有索引签名的接口(interface),例如 MixinDescriptor .这是一个 known and currently intended行为。处理它的最简单方法可能是更改 ITime来自 interfacetype .

最后,你的 mixin 可能需要修复,因为你的 time()函数实现引用了一个名为 chance 的变量这似乎没有定义。我想代码在运行时会抛出错误,但也许您没有包含所有相关代码或者它只是一个示例。以面值取代码,也许可以代替 chance你应该使用 this (并通过使用类型为 this Chance parameter 来保持 TypeScript 开心)?喜欢
function time(this: Chance.Chance) {
const h = this.hour({ twentyfour: true });
const m = this.minute();
return `${h}:${m}`;
};

无论如何,这是我可以在不安装 ChanceJS 的情况下给出的最接近的答案。希望它能让你指向正确的方向。祝你好运!

关于typescript - 在 TypeScript 中构建机会 Mixin,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50221048/

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