定义对象

interface UserInterface {
  name:string,
  age:number
}

type UserType = {
  name: string
  age: number
}

定义函数

interface addInterface {
  (count:number):number
}

type addType = (count:number):number

函数属性

interface PeopleInterface {
  (name:string,age:number):void,//构造函数
  say():void,//普通函数
  read(book:string):void
}

type PeopleType = {
  (name:string,age:number):void,//构造函数
  say():void,//普通函数
  read(book:string):void
}

//使用
const mike:PeopleInterface = function(name:string,age:number) {}
mike.say = function(){}
mike.read = function(book:string){}

继承|交叉类型

interface UserInterface {
  name:string,
  age:number
}

type UserType = {
  name: string
  age: number
}

//interface继承interface
interface Admin extends UserInterface {
  isAuthed:boolean
}
//interface继承type
interface Admin extends UserType { 
  isAuthed:boolean
}
//type继承type
type Admin = UserType & {
  isAuthed:boolean
}
//type继承interface
type Admin = UserInterface & {
  isAuthed:boolean
}

泛型

interface UserInterface<T>{
  name:string,
  age:T
}
type UserType<T> = {
  name:string,
  age:T
}
const Admin:UserInterface<string> = {
  name:'mike',
  age:'10'
}
const Admin2:UserType<number> = {
  name:'mike',
  age:10
}

基本类型别名(interface无法实现)

type Name = string

元组类型(interface无法实现)

type arr = [string,number]

联合类型(interface无法实现)

//普通类型联合
type Nullable = null|undefined
//对象类型联合
type Dog = {
  wang():void
}
interface Cat {
  miao():void
}
type MyPet = Dog|Cat

类型赋值(interface无法实现)

type DocumentBody = typeof document.body

声明合并(type无法实现)

interface User {
  name:string
}
interface User {
  age:string
}
//等价为
interface User {
  name:string
  age:string
}

属性冲突

interface UserInterface {
  name:string
  age:number,
}
interface UserInterface {
  age:string//报错Subsequent property declarations must have the same type.  Property 'age' must be of type 'number', but here has type 'string'
}

type UserType1 = {
  name:string
  age:number,
}
type UserType2 = {
  age:string,
}
type UserType = UserType1&UserType2
//不报错,等价于
type UserType = {
  name:string
  age:number&string,//number&string等价于never
}
const user:UserType = {
  name: 'mike',
  age: (() => { throw new Error('exception') })()
}
posted on 2022-03-04 10:20  吞天泡泡龙  阅读(78)  评论(0编辑  收藏  举报