为 Record<string, string> 分配接口或类型的打字稿 [英] Typescript assigning an interface or a type to a Record&lt;string, string&gt;

查看:259
本文介绍了为 Record<string, string> 分配接口或类型的打字稿的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

阅读这个问题这篇文章,我仍然对 之间的细微差别感到困惑接口类型.

After reading this question or this article, I'm still a bit confused about the subtle differences between an interface and a type.

在这个例子中,我的目标是将一个简单的对象分配给更广泛的 Record 类型:

In this example, my goal is to assign a simple object to a broader Record<string, string> type:

interface MyInterface {
  foobar: string;
}

type MyType = {
  foobar: string;
}

const exampleInterface: MyInterface = { foobar: 'hello world' };
const exampleType: MyType = { foobar: 'hello world' };

let record: Record<string, string> = {};

record = exampleType;      // Compiles
record = exampleInterface; // Index signature is missing

尝试

使用type 声明我的对象时可以进行赋值,但使用interface 声明类似的对象时则不能.它说缺少索引签名,但就我对索引签名的(有限)理解而言,MyTypeMyInterface 实际上都没有.

The assignment is possible when declaring my object with a type, but not when declaring a similar one with an interface. It says that the index signature is missing, but to my (limited) understanding of index signatures, none of MyType and MyInterface actually have one.

最后一行没有编译而前一行编译的原因是什么?

What is the reason why the last line does not compile whereas the previous one does?

推荐答案

Record{ [key: string]: string } 相同.只有当该类型的所有属性都已知并且可以根据该索引签名进行检查时,才允许将子集分配给该索引签名类型.在您的情况下,exampleType 中的所有内容都可以分配给 Record.这只能检查对象文字类型,因为一旦声明对象文字类型就无法更改.因此,索引签名是已知的.

Record<string, string> is the same as { [key: string]: string }. A subset is allowed to be assigned to this index signature type is only possible if all properties of that type are known and can be checked against this index signature. In your case, everything from exampleType is assignable to Record<string, string>. This can be only checked for object literal types, as object literal types can't be changed once you declared them. Thus, the index signature is known.

来源:https://github.com/microsoft/TypeScript/pull/7029

相反,接口在你声明它们的那一刻就不是最终的.由于声明合并,总是有可能向同一接口添加新成员.

In contrast, interfaces are not final the moment you declare them. There is always the possibility of adding new members to the same interface due to declaration merging.

这篇关于为 Record<string, string> 分配接口或类型的打字稿的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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