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 定义的类型,等同于是创建了一个新的类型结构。

posted @   Simon9527  阅读(51)  评论(0编辑  收藏  举报
努力加载评论中...
点击右上角即可分享
微信分享提示