gpt4 book ai didi

javascript - 您将如何为 x-tag 组件定义 Typescript 接口(interface)签名

转载 作者:行者123 更新时间:2023-11-30 12:50:01 24 4
gpt4 key购买 nike

x-tag 规范在纯 JS 中具有以下签名 -

xtag.register('x-accordion', {
// extend existing elements
extends: 'div',
mixins: ['superdefaults', 'otherdefaults'],
lifecycle:{
created: function(){
// fired once at the time a component
// is initially created or parsed
},
inserted: function(){
// fired each time a component
// is inserted into the DOM
},
removed: function(){
// fired each time an element
// is removed from DOM
},
attributeChanged: function(){
// fired when attributes are set
}
},
events: {
'click:delegate(x-toggler)': function(){
// activate a clicked toggler
}
},
accessors: {
'togglers': {
get: function(){
// return all toggler children
},
set: function(value){
// set the toggler children
}
}
},
methods: {
nextToggler: function(){
// activate the next toggler
},
previousToggler: function(){
// activate the previous toggler
}
}
});

显然,方法、访问器和事件可以有多个条目。

我正在尝试定义传递给 register 函数的对象字面量的 Typescript 等价物。任何人都知道如何实现这一点?

最佳答案

方法、访问器和事件的秘诀在于使用字符串索引器。我本来打算只写那部分,但最后还是写了大部分,所以我把它写完了。

declare module xtag {
interface RegisterParams {
extends?: string;
prototype?: any;
mixins?: string[];
lifecycle?: {
created?: () => void;
inserted?: () => void;
removed?: () => void;
attributeChanged?: () => void;
}
events: { [name: string]: () => void; };
accessors: {[name: string]: {
get?: () => any;
set?: (value: any) => any;
attribute?: any;
}};
methods: { [name: string]: () => void; }
}
export function register(tagName: string, params: RegisterParams): void;
}

索引器有一个很好的解释 here .在 accessors 上,无法表达 get 和 set 与属性互斥。我们能做的最好的事情就是让它们成为可选的。

关于javascript - 您将如何为 x-tag 组件定义 Typescript 接口(interface)签名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21281896/

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