TypeScript:实现具有调用签名和索引签名的接口 [英] TypeScript: Implement an interface with both call signature and indexing signature

查看:29
本文介绍了TypeScript:实现具有调用签名和索引签名的接口的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个满足这种类型的对象:

I would like to create an object that satisfies this type:

interface I {
    (): string;
    [x: string]: number;
}

并通过 TypeScript 类型检查.理想情况下,我不想诉诸技巧,例如使用 any 作为中间步骤.

and passes TypeScript type checking. Ideally I would like to not need to resort to tricks such as using any as an intermediate step.

我知道可以向具有调用签名的接口添加其他字段,如下所述:使用裸函数签名和其他字段实现 TypeScript 接口.

I know additional fields can be added to an interface having a call signature, as described here: Implementing TypeScript interface with bare function signature plus other fields.

我试着写:

const foo: I = Object.assign(
    // Callable signature implementation
    () => 'hi',
    {
        // Additional properties
        text2: 3
    }
)

但我收到错误:Type '(() => "hi") &{ 文本 2:数字;}' 不能分配给类型 'I'.类型 '(() => "hi") & 中缺少索引签名{ 文本 2:数字;}'.

我很想知道是否有办法创建一个实现接口 I 的对象.

I'd be curious to know if there's a way to create an object implementing interface I.

推荐答案

如果您不将类型定义为接口而是定义为交集类型的类型别名,则无需断言即可执行此操作:

You can do this without an assertion if you don't define the type as an interface but rather a type alias for an intersection type:

type I =  {
    (): string;
} & {
    [x: string]: number;
}
// Will work
let d:I= Object.assign(function() { return ""}, {
    text: 10
});

不确定为什么一个有效而另一个无效,它们的公共结构本质上是相同的,这可能是编译器错误.

Not sure why one works but not the other, their public structure is essentially the same, it could be a compiler bug.

编辑提交了一个错误,我们将有等待回复

Edit Submitted a bug we'll have to wait for a reply

这篇关于TypeScript:实现具有调用签名和索引签名的接口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆