1、在Ts中,我们可以通过type和interface的方式去定义类型,一般情况下通过interface接口的方法定义的类型都可以通过type去定义。注意type要添加等号。Interface定义类型不需要添加等号。

下面代码是用type声明一个string类型的例子

type user=string
//接收一个字符串类型的数据,返回一个user类型(字符串类型)的数据
function Input(str:string):user{
    return str.slice(0,2)
}
//把返回结果赋值给userInput
let userInput=Input('hello')
//重新给其赋值一个字符串类型的值,没有报错,说明用type声明的字符串类型生效
userInput='new'

下面代码是用interface声明一个对象类型的例子

interface Point{
    x:number,
    y:number
}
//接收一个Point的对象类型数据
function printCoord(pt:Point){

}
//给函数传一个对象类型的数据,没有报错,说明用interface声明的类型生效
printCoord({
    x:100,
    y:100
})

2、 Interface扩展接口:可以在interface后面添加关键字extends去扩展接口。类型别名type需要使用&符号去扩展接口

下面代码是用extends扩展接口的例子

//扩展接口
interface Animal{
    name:string
}
interface Bear extends Animal{
    honey:boolean
}
//声明一个类型为Bear类型的对象,要求既要有name,也要有honey。说明用extends扩展接口成功
const bear:Bear={
    name:'winie',
    honey:true
}
console.log(bear.name);
console.log(bear.honey);

 下面代码是用type扩展接口的例子

//扩展类型
type Animal={
    name:string
}
//给Animal扩展接口
type Bear=Animal&{
    honey:boolean
}
const bear:Bear={
    name:'winie',
    honey:true
}

3、向现有类型添加新字段,interface可以通过定义同名的方式去扩展字段,类型别名type是不能通过同名的方式去进行扩展的。

下面代码是interface通过定义同名的方式向现有类型添加新字段

//向现有的类型添加新字段
interface MyWindow{
    title:string
}
interface MyWindow{
    count:number
}
const w:MyWindow={
    title:'wz',
    count:666
}

 下面代码会报错,因为类型别名type是不能通过同名的方式去进行扩展的。

//类型创建后不能更改
type MyWindow={
    title:string
}
type MyWindow={

}

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐