interface 定义
interface i_Tree{
leftLeaf: string
rightLeaf: string
}
// 作为类型定义
const tree: i_Tree = {
leftLeaf: 'left',
rightLeaf: 'right'
}
可选属性
interface Man{
name: string // 必选
job?: string // 可选
}
只读
interface Man{
readonly sex:string
name: string
job?: string
}
函数描述
interface i_talk{
(msg:string): void;
}
const talk:i_talk = (msg: string) => {
console.log(msg)
}
可索引
interface i_list{
[index: number]: string
}
const li: i_list = ['ni', 'mi']
类描述
interface i_Man{
name: string
}
class Man implements i_Man{
name:string
constructor(name: string) {
this.name = name
}
}
const c = new Man('cc')
console.log(c.name)
类构造器描述
interface i_Man{
name: string
}
class Man implements i_Man{
name:string
constructor(name: string) {
this.name = name
}
}
// 定义构造函数接口
interface i_ManConstructor{
new (name:string): i_Man
}
// 接收类定义作为参数
function createMan(c: i_ManConstructor, name: string):i_Man{
return new c(name)
}
混合类型
interface i_talk{
(msg?: string): void
defaultMsg?: string
}
const talk: i_talk = function (msg?: string): void{
console.log(msg || talk.defaultMsg)
}
talk.defaultMsg = 'not find msg'
talk()
// 函数也是对象,可以拥有自己的属性
继承接口
interface i_A{
propA: string
}
interface i_B{
propB: string
}
interface i_C extends i_A, i_B{
propC: string
}
const c: i_C = {
propA: 'a',
propB: 'b',
propC: 'c',
}
继承类
class Control {
private state: any;
}
interface SelectableControl extends Control {
select(): void;
}
class Button extends Control implements SelectableControl {
select() { }
}
class TextBox extends Control {
select() { }
}
// 错误:“Image”类型缺少“state”属性。
class Image implements SelectableControl {
select() { }
}
class Location {}
网友评论