前言:我们的团队正在建立一个建立在d3之上的图书馆。由于我们使用的是TypeScript,因此我们也使用了DefinitelyTyped中的d3类型。当尝试使用ScaleOrdinal等界面时,会出现以下问题。
假设我们有一个包含调用签名和其他属性的接口:
export interface Foo<T> {
// Let's pretend this will be the identity function
(arg: T): T;
// Let's pretend that this will be a no-op function
// Note that this returns "this"
doFoo(): this;
}
我们如何正确地以类型安全的方式实现这样的接口[1]?经过研究,我发现了以下相关问题,所有这些问题都略有不同和/或相当陈旧。我想知道我们是否遗漏了某些内容或者是否在这里向TypeScript团队提出问题:
请注意,界面在我们外部,因此实现它是我们唯一的选择。
¹为了问题,我希望实现明确重述所有类型的注释。
在声明函数的最近版本的typescript(3.2或3.3不确定哪些)时,您还可以为函数分配额外的属性,而typescript会将这些作为这些属性的定义,而不是抱怨它们没有被定义:
export interface Foo<T> {
(arg: T): T;
doFoo(): this;
}
function foo(arg: number) : number {
return arg
}
foo.doFoo = function <TThis extends typeof foo>(this: TThis): TThis { // no polymorphic this in simple functions
return this
}
let o: Foo<number> = foo; // foo is compatible with Foo<number>
旧的是这样做,仍然有效使用Object.assign
创建具有额外属性的函数:
let o: Foo<number> = Object.assign(function (arg: number): number {
return arg
}, {
doFoo: function <TThis>(this: TThis): TThis {
return this
}
})