自定义模块模式的TypeScript类型定义

迈克尔·威尔逊

我正在尝试为我在这里继承的自定义构建模块规范编写类型定义。无法弄清楚。的诀窍在于,上下文在计算出的上下文功能应该从被驱动特性,使得shouldBeValueA从驱动KEYA

define.model("moduleName",
[
    "jquery"
],
function($) {
    return this.viewModel({
        pub: {
            properties: {
                keyA: "valueA"
            },
            functions: {
                keyB: this.computed(function() {
                    var shouldBeValueA = this.keyA;
                })
            }
        }
    })
})

到目前为止最好的定义:

interface Define {
model: (
    name: string,
    dependencies: string[],
    moduleContext: <T>(this: {
        computed: (context: (this: T) => any) => KnockoutComputed<any>,
        viewModel: (options: {
            pub: {
                properties: T,
                functions: any
            },
        }) => any;
    },
    ...args) => void) => void;
}

declare var define: Define;

但是,此错误:“类型T上不存在属性keyA”

迈克尔·威尔逊

我不确定这是否会对其他人有帮助,但是@kingdaro是正确的,该模式与vue.js API非常相似。我最终建立了一个受该模式启发的类型定义。

interface RequireDefine {
    model<TPubProps, TPubFuncs, TPrivProps, TPrivFuncs>(
        name: string,
        deps: string[],
        factory: (
            this: {
                viewModel<TPubProps, TPubFuncs, TPrivProps, TPrivFuncs>(
                    options: ThisTypedViewModelOptions<TPubProps, TPubFuncs, TPrivProps, TPrivFuncs>
                ): TPubProps & TPubFuncs
    ): any
}

type ThisTypedViewModelOptions<TPubProps, TPubFuncs, TPrivProps, TPrivFuncs> =
    object
    & ViewModelOptions<TPubProps, TPubFuncs, TPrivProps, TPrivFuncs>
    & ThisType<CombinedViewModelInstance<TPubProps, TPubFuncs, TPrivProps, TPrivFuncs>>

type CombinedViewModelInstance<TPubProps, TPubFuncs, TPrivProps, TPrivFuncs> = TPubProps & TPubFuncs & { priv: () => TPrivProps & TPrivFuncs }    

type DefaultMethods = { [key: string]: (...args: any[]) => any };

interface ViewModelOptions<
    TPubProps = object,
    TPubFuncs = DefaultMethods,
    TPrivProps = object,
    TPrivFuncs = DefaultMethods
    > {

    ctor?: (options?: any) => void,
    pub?: {
        properties?: TPubProps,
        functions?: TPubFuncs
    },
    priv?: {
        properties?: TPrivProps,
        functions?: TPrivFuncs
    }
}

虽然还不是很完美,但是将vue类型适应此视图模型结构还是一个很好的学习经验。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章