7.接口和函数
接口和函数
一、约束函数参数类型
interface Person {
name: string;
age: number;
}
function foo(student: Person) {
}
foo({ name: '张三', age: 20 })
二、约束函数返回值类型
interface Person {
name: string;
age: number;
}
function foo(student: Person): Person {
return student;
}
foo({ name: '张三', age: 20 })
三、约束函数的类型
基础语法:
interface 接口名 {
(参数名: 数据类型): 返回值类型
}
示例代码:
interface Foo {
(student: Person): Person
}
const foo: Foo = (student) => {
return student;
}
foo({ name: '张三', age: 20 })
四、接口中使用接口
interface Person {
name: string;
age: number;
}
interface Foo {
(student: Person): Person
}
const foo: Foo = (student) => {
return student;
}
foo({ name: '张三', age: 20 })
五、type 和 interface 的区别
type,是对已存在的类型取一个新的名字,并不会创建一个新的类型出来,常用于联合类型。
interface ,常用于定义对象的类型约束,通过 interface 定义的类型,等同于是创建了一个新的类型结构。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步