react中interface 自定义的静态类型

本文介绍了在React中如何使用typescript的interface定义静态类型,包括创建只读属性、可选属性、任意属性的接口,以及接口在类中的应用、接口继承、接口作为函数类型等。通过实例展示了interface在函数参数和类实现中的使用方式,强调了类型检查的重要性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

// 接口  自定义的静态类型

// 只能是对象或者函数

// 1 定义接口

interface person {

    //  readonly key 作用:设置某个属性为只读类型, 只要修改key就会报错

    readonly name: string,

    // key? 作用:设置某个属性可有可无

    age?: number,

    // propName 作用 传入不确定的属性

    [propName: string]: any,

    // say函数,返回值为string

    say(): string

}

// 使用接口

function getPerson(person: person): string { // 表示person 中必须有name 为 string

    console.log(person.name)

    // person.name = 'asdfasdf';  // 报错

    return person.name

}

getPerson({

    name: 'aa',

    aa: 123,

    say() {

        return ''

    }

})

// 2 在类中使用接口

// implements interfaceName  在类使用接口

// 注意: 类中必须具备接口中属性。

class user implements person {

    cname = 'aa';

    name = '123';

    // say = 123

    say() {

        return 'aaa'

    }

}

// 3接口继承  extends

interface zy {

    name: string

    age?: number

}

// blc继承了 zy

interface blc extends zy {

    dec: string

}

// obj 赋值时,也需要加入zy接口中属性

let obj: blc = {

    dec: 'woshi dfds',

    name: '',

    age: 34

}

// 4 接口为函数时候

//  sayHollow 是函数

interface sayHollow {

    // 形参为 string类型  返回值为字符串类型

    (word: string): string

}

// let say:sayHollow = {}  // bug

// 要求 say变量赋值为 函数 并且返回值为字符串;执行时候,实参为字符串

let say:sayHollow = function(a){

    console.log(a);

    return ''

}

// say(123) //  bug  123类型不对

say('123')


 

// let foo:(a:string)=>string = (a)=>{

//     return ''

// }

// let foo1:(b:number,a:string)=>string = function(b,a){

//     return '123'

// }

// foo1(1,'12')

interface a {

    (zidingyi:string):string

}

let foo:a = (a)=>{

    return ''

}

interface b{

    (b:number,a:string):string

}

let foo1:b = function(b,a){

    return '123'

}

foo1(1,'12')



 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

鲤忆

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值