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

一、Interface与type的区别

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

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

2、类型扩展的方式不同

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

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

interface SomeObjs {

    //声明属性和对应类型

}


type PrimitiveTypes = number | string

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

在利用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<string,string> = {}

//正常编译
record = obj1

//报错:index signature missing
record = obj2

可以理解为:

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

而type则不存在这类隐患!

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

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

}

相关推荐

  1. ts中typeinterface类型声明区别

    2024-07-16 01:54:02       61 阅读
  2. TypeScript中interfacetype区别

    2024-07-16 01:54:02       46 阅读
  3. GPT每日面试题-Typescript中typeinterface区别

    2024-07-16 01:54:02       33 阅读
  4. TypeScript中interfacetype差别是什么?

    2024-07-16 01:54:02       37 阅读
  5. Python中,type() isinstance() 区别

    2024-07-16 01:54:02       41 阅读
  6. Ts 接口interface 与 对象type 异同

    2024-07-16 01:54:02       74 阅读
  7. 正排索引倒排索引区别

    2024-07-16 01:54:02       24 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-07-16 01:54:02       67 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-07-16 01:54:02       72 阅读
  3. 在Django里面运行非项目文件

    2024-07-16 01:54:02       58 阅读
  4. Python语言-面向对象

    2024-07-16 01:54:02       69 阅读

热门阅读

  1. vue2与vue3的区别

    2024-07-16 01:54:02       21 阅读
  2. 安卓热门面试题一

    2024-07-16 01:54:02       20 阅读
  3. 书籍跳跃游戏(4)0715

    2024-07-16 01:54:02       16 阅读
  4. livecd工具下载地址

    2024-07-16 01:54:02       18 阅读
  5. 网站架构核心要素

    2024-07-16 01:54:02       19 阅读
  6. postman实现接口关联

    2024-07-16 01:54:02       18 阅读
  7. IPython 使用技巧整合

    2024-07-16 01:54:02       19 阅读