typescript

82 阅读1分钟

对象声明

 // 譬如对象格式


方法1: type OPTIONS_TYPE = Record<string, any>

方法2: interface OPTIONS_TYPE  {
  [key: string]: any
}

方法3:这种限制了不多不少必须是testA/testB/testC, 
type TestTypes = 'testA' | 'testB' | 'testC'
type OPTIONS_TYPE =  {
 [key in TestTypes] : any
}

方法4: 这种更精确,到值的类型
interface OPTIONS_TYPE {
    testA: number,
    testB: string,
    testC: boolean
}

const options: OPTIONS_TYPE = {
    testA: 1,
    testB: '2',
    testC: true
}


type与interface区别

写法:type 后面直接是 =,interface 是对象{}

声明类型:type 可以描述任何类型组合,interface 只能描述对象结构;

继承结构: interface 可以继承自(extends)interface 或对象结构的 type。type 也可以通过 & 做对象结构的继承;

类型合并:多次声明的同名 interface 会进行声明合并,type 则不允许多次声明;

implements与extend区别

implements:实现一个新的类,从父类或者接口实现所有的属性和方法,同时可以重写属性和方法,包含一些新的功能, 一个类通过关键字implements声明自己使用一个或者多个接口。

extends: 继承一个新的接口或者类,从父类或者接口继承所有的属性和方法,不可以重写属性,但可以重写方法

interface Base {
  testString: String;
  testNumber: number;
}

interface IExtends extends Base { // 接口继承接口
  testBoolean: Boolean
}

class CImplements implements Base { // 类实现接口
  testString: String
  testNumber: number
}

interface CInterface extends CImplements { // 接口继承类
  testBoolean: Boolean
}