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表示只读不能修改