javascript - 是否可以在 typescript 的可索引类型接口(interface)中定义函数?

标签 javascript typescript

我想定义以下内容:

export interface IValidationContextIndex {
    [validationContextKey: string]: ValidationContext;
    getValidationContexts(): Array<ValidationContext>;
}

这样我就可以获得一个遵循 IValidationContextIndex 接口(interface)的对象,并对其调用 getValidationContexts

但是 VSCode 对这种类型的定义不满意。是否可以在界面中执行此操作,或者我是否需要类似的内容:

class cache {
    constructor(public index: IValidationContextIndex ) {};
    getValidationContexts() {return Object.value(<any> index)}
} 

最佳答案

问题是 typescript 希望索引签名与所有声明的成员保持一致。因为您也可以使用索引访问 getValidationContexts 成员,并且它的类型不会是 ValidationContext

您可以使索引签名与定义的成员一致,但这并不理想,因为您需要缩小返回类型:

export interface IValidationContextIndex {
    [validationContextKey: string]: ValidationContext | (() => Array<ValidationContext>);
    getValidationContexts(): Array<ValidationContext>;
}

绕过此限制的一种方法是使用交集类型:

type IValidationContextIndex = {
    [validationContextKey: string]: ValidationContext;
} & {
    getValidationContexts(): Array<ValidationContext>;
}

但是由于同样的索引不兼容原因,无法直接创建这种类型的对象。您需要使用 Object.assign 创建对象:

let o : IValidationContextIndex = Object.assign({ a: new ValidationContext() }, {
    getValidationContexts(): Array<ValidationContext> {
        return Object.values(this)as any
    }
});

或者使用类型断言:

let o : IValidationContextIndex = {
    getValidationContexts(): Array<ValidationContext> {
        return Object.values(this)as any
    }
} as IValidationContextIndex;

关于javascript - 是否可以在 typescript 的可索引类型接口(interface)中定义函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51072023/

相关文章:

javascript - 单击下一页折叠 Accordion 菜单

javascript - Ember : Model as content for CollectionView

javascript - 对于实时 Web 应用程序,我有什么比 websockets 更快的替代方法?

javascript - 如何在 Angular 4 中进行 i18n 翻译以获得动态值?

javascript - 将对象传递给护照的 require() 时出现类型错误

javascript - 在 ExtJs 树中搜索节点

Angular - 在返回的 JSON 数组中强制执行模型格式

arrays - 为什么我可以调用 array.some() 而不是 array.every() 联合数组类型?

reactjs - typescript React/Redux : Argument of type 'typeof MyClass' is not assignable to parameter of type 'ComponentType<...'

typescript - Typescript中函数声明的区别