Typescript 使用fluent/chaining API的JS库的类型脚本定义文件(.d.ts)
我正在为使用方法链接的JS库编写一个定义文件。但是,由于它还使用/重用抽象基类,所以它的方式比我以前看到的稍微复杂一些。所以我采用了这种方法:Typescript 使用fluent/chaining API的JS库的类型脚本定义文件(.d.ts),typescript,Typescript,我正在为使用方法链接的JS库编写一个定义文件。但是,由于它还使用/重用抽象基类,所以它的方式比我以前看到的稍微复杂一些。所以我采用了这种方法: // the test.d.ts declare module someJSChainingLib { export interface IbaseA <T>{ function1: () => T; } export interface IbaseB<T> { function2: (
// the test.d.ts
declare module someJSChainingLib {
export interface IbaseA <T>{
function1: () => T;
}
export interface IbaseB<T> {
function2: () => T;
}
export interface IbaseC<T> {
function3: () => T;
}
export interface IbaseD<T> {
function4: () => T;
}
export interface ICombinator1 extends IbaseA<ICombinator1>, IbaseB<ICombinator1>, IbaseC<ICombinator1> {
// possibly add more stuff here
}
export interface ICombinator2 extends IbaseA<ICombinator2>, IbaseB<ICombinator2>, IbaseD<ICombinator2> {
// possibly add more stuff here
}
export interface IFeature1 extends ICombinator1 {
// this has the base interfaces A,B,C
// possibly add more stuff here
}
export interface IFeature2 extends ICombinator2 {
// this has the base interfaces A,B,D
// possibly add more stuff here
}
}
//test.d.ts
声明模块someJSChainingLib{
出口接口{
函数1:()=>T;
}
导出接口IbaseB{
函数2:()=>T;
}
导出接口IbaseC{
函数3:()=>T;
}
导出接口IbaseD{
函数4:()=>T;
}
导出接口ICombinator1扩展了IbaseA、IbaseB、IbaseC{
//可能在这里添加更多内容
}
导出接口ICombinator2扩展了IbaseA、IbaseB、IbaseD{
//可能在这里添加更多内容
}
导出接口IFeature1扩展了ICombinator1{
//这有基本接口A、B、C
//可能在这里添加更多内容
}
导出接口IFeature2扩展了ICombinator2{
//这有基本接口A、B、D
//可能在这里添加更多内容
}
}
在消费方面,它看起来是这样的:
///<reference path="test.d.ts" />
function callit() {
var test1: someJSChainingLib.IFeature1;
test1.function1().function2().function3();
var test2: someJSChainingLib.IFeature2;
test2.function1().function2().function4();
}
///
函数callit(){
var test1:someJSChainingLib.IFeature1;
test1.function1().function2().function3();
var test2:someJSChainingLib.IFeature2;
test2.function1().function2().function4();
}
这些特性重复使用一些基本接口,并根据需要将它们混合使用。我想知道是否有更好的方法来输入这个?或者如果仿制药是一条出路?斯蒂芬•钟的评论:
我不认为泛型与此相关,除非您的 “功能”实际上是不同类型的相同实现。
YouWay是模拟mixin支持的“官方”方式 TypeScript(直到它具有真正的mixin语法),所以我认为 看起来不错
是答案,所以我在这里“回答”是为了让问题不再显示为未回答的问题。我认为泛型在这里不相关,除非您不同的“函数”实际上是不同类型的同一实现。您的方式是用TypeScript模拟混合支持的“官方”方式(直到它具有真正的mixin语法),所以我认为它看起来很好。嗨,Stephen,谢谢你的回答!是的,这就是它们,所有不同类型的功能的实现都是相同的。因此在feature1的上下文中,返回的实例是feature1类型,在feature2的上下文中,返回的实例是feature2类型。感觉你在这里做错了什么。为什么要将函数合并到interfaceA和interfaceB中?您试图在这里构建的逻辑是什么?也许您可以相应地构建结构。@gilamran:这是js中一种称为mixin的常见模式,不同的“对象”共享函数,dc.js()是这项技术的一个很好的例子,我只是编写了typescript定义来描述行为。