【Typescript】Interface和type的区别;探讨为什么interface赋值给Record需要索引签名

16,700次阅读
没有评论

共计 1008 个字符,预计需要花费 3 分钟才能阅读完成。

一、Interface 与 type 的区别

1、Interface 可以声明合并,type 不行

声明同名的类型,Interface 同名会合并,而 type 重名会报错

【Typescript】Interface 和 type 的区别;探讨为什么 interface 赋值给 Record 需要索引签名

* 注意:如果 interface 合并的时候,同名属性值对应的类型不兼容,则会报错!

例如:

interface P1{name: string;}

interface P1{name: number;}


//throw error!!!

2、类型扩展的方式不同

Interface 基于 extends 继承扩展基类类型,而 type 利用 & 交集 扩展

【Typescript】Interface 和 type 的区别;探讨为什么 interface 赋值给 Record 需要索引签名

 * 注意:如果定义 type 的交集类型时,同名属性值对应的类型存在冲突,会导致类型变为never

例如:

【Typescript】Interface 和 type 的区别;探讨为什么 interface 赋值给 Record 需要索引签名

3、type 可以被基础类型定义,而 interface 仅可以描述对象结构的类型

interface SomeObjs {// 声明属性和对应类型}


type PrimitiveTypes = number | string

二、探讨为什么 interface 赋值给 Record 需要索引签名

索引签名:对数组或者对象等索引值以及索引返回值进行通用类型定义。其索引值可接受的类型有string、number、symbol

在利用 type Record 定义一系列属性和对应类型的时候,interface 需要添加索引签名而 type 不用

例如:

interface MyInterface {foo : string;}

type MyType = {foo : string;}

const obj1 : MyInterface = {foo : 'obj1'}
const obj2 : MyType = {foo : 'obj2'} 

let record : Record = {}

// 正常编译
record = obj1

// 报错:index signature missing
record = obj2

可以理解为:

Record 限制了属性的类型和值的类型。而 Interface 由于可以声明合并,因此此刻的 MyInterface 并不一定是最终的类型结构,后续的合并可能会存在类型不与 Record 一致的情况

而 type 则不存在这类隐患!

因此为和 Record 匹配,MyInterface 应添加索引签名,对属性和值的类型进行检查,写为:

interface MyInterface { 
    foo : string;
    [key : string] : string;

}

原文地址: 【Typescript】Interface 和 type 的区别;探讨为什么 interface 赋值给 Record 需要索引签名

    正文完
     0
    Yojack
    版权声明:本篇文章由 Yojack 于2024-11-07发表,共计1008字。
    转载说明:
    1 本网站名称:优杰开发笔记
    2 本站永久网址:https://yojack.cn
    3 本网站的文章部分内容可能来源于网络,仅供大家学习与参考,如有侵权,请联系站长进行删除处理。
    4 本站一切资源不代表本站立场,并不代表本站赞同其观点和对其真实性负责。
    5 本站所有内容均可转载及分享, 但请注明出处
    6 我们始终尊重原创作者的版权,所有文章在发布时,均尽可能注明出处与作者。
    7 站长邮箱:laylwenl@gmail.com
    评论(没有评论)