TypeScript基础知识(5) TypeScript接口(可选成员,只读成员)

本文介绍了TypeScript接口中的可选成员和只读成员概念。可选成员允许对象结构中存在非必需的属性,如`subtitle`,而只读成员如`summary`则确保属性在创建后不能被修改。TypeScript接口主要用于定义对象结构,并在编译后不体现在JavaScript代码中,仅用于类型检查。

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

TypeScript接口(可选成员,只读成员)

interfaces翻译过来就是接口,可以理解成规范或者是契约,可以用来约定对象的结构,我们去使用一个接口就必须要去遵循接口的全部规定。 TypeScript接口最直观的提现就是可以去约定一个对象当中具体有哪些成员,成员的类型又是什么样子。我们看下下面的例子。

interface Post {
    title:string
    content:string

}
function printPost(post:Post){
    console.log(post.title);
    console.log(post.content);
}
printPost({
    title:'Hello TypeScript',
    content:'Good job'
})

编译下以上代码,

"use strict";
function printPost(post) {
    console.log(post.title);
    console.log(post.content);
}
printPost({
    title: 'Hello TypeScript',
    content: 'Good job'
});

我们可以发现js文件中是没有关于接口的代码的,所以说 TypeScript接口只是用来为我们有结构的数据进行类型约束的。所以实际运行接口不会出现在js代码里。

可选成员,只读成员

举个例子

interface Post {
    title:string
    content:string
    subtitle?:string//副标题加个问号表示可有可无(Post.subtitle?: string | undefined)其实就是添加了undefined属性
    readonly summary: string//readonly表示在初始化过后就不能修改了
}
function printPost(post:Post){
    console.log(post.title);
    console.log(post.content);
}
printPost({
    title:'Hello TypeScript',
    content:'Good job',
    summary:'文章摘要'
})

可选成员: subtitle表示副标题可有可无其实就是添加了undefined属性
只读成员:summary表示只读不能修改

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值