接口类型
interface labelValue {
label: string
}
// 未使用接口以前
function printLabel(labelObj: {label: string}) {
console.log(labelObj.label)
}
// 使用接口以后
function printLabel(labelObj: labelValue) {
console.log(labelObj.label)
}
// 存在这个参数且类型相同即可,顺序和参数数量不限制
let obj = {label: 'string', number: 1}
printLabel(obj) // right
interface labelParams {
str? : string, // 可选
readonly str2: string, // 只读
[propname: string]: amy // 任意数量属性
}
// 额外扩展
let ro: ReadonlyArray<number> = [1, 2, ,3, 4] // 不可修改,并且不可把可读数组赋值给普通数组
interface SearchFunc {
(source: string, subString: string): boolean
}
let mySearch: SearchFunc
// 只要参数数量和类型相同
mySearch = function(str1: string, str2: string): boolean {
...
return true
}
interface StringArray {
[index: number]: string
}
let myArray = StringArray
myArray = ['Bob', 'Fred']
let myStr: string = myArray[0]
interface ClockInterface {
currentTime: Date
setTime(: Date)
}
class Clock implements ClockInterface {
currentTime: Date
constructor() {
}
setTime(d: Date) {
this.currentTime = d
]
}
interface ClockInterface { // 实例部分
tick()
}
interface ClockConstructor { // 静态部分
new(hour: number, minute: number): ClockInterface
}
function createClock(ctor: ClockConstructor, hour: number, minute: number) {
return new ctor(hour, minute)
}
class DigitalClock implements ClockInterface {
constructor(h: number, m: number) {}
tick() { console.log('digital') }
}
class AnalogClock implements ClockInterface {
constructor(h: number, m: number) {}
tick() { console.log('analog') }
}
let digital = createClock(DigitlClock, 12, 7)
let analog = createClock(AnalogClock, 11, 6)
interface Shap {
color: string
}
interface PenStroke {
penWidth: number
}
interface Square extends Shap, PenStroke {
sideLength: number
}
let square = {} as Square
square.color = 'blue'
square.penWidth = 10
square.sideLength = 111
class Control {
private state: string
}
interface SelectControl extends Control {
select()
}
class Button extends Control implements SelectControl {
slect() {}
}
class ImageC implement SelectControl { // 报错 没有继承Control中的私有成员 只有Control的子类,继承SelectControl不会报错
}
interface Counter {
(star: number): string
interval: number
reset(): void
}
function getCount: Counter {
let counter = (function (star: number) {
}) as Counter
counter.interval = 123
counter.reset = function() {
}
return counter
}
let c = getCount()
c(10)
c.reset()
c.interval = 5
// 未使用泛型以前,想输入number返回也是number
function identity(arg: number): number {
return arg
}
// 使用泛型后
function identity<T>(arg: T): T {
return arg
}
let myIdentity: <T>(arg: T) => T = identity
let myIdentity2 : {<T>(arg:T): T} = identity //或者这么使用
// 使用泛型接口后
interface GeneIdentity {
<T>(arg: T): T
}
let myIdentity2: GeneIdentity<number> = identity // 推荐使用