断言用武之地
let someValue: any = 'this is string'
someValue.length // 编译器找不到这个api
// 如何让它找到 使用断言
let strLength: number = (someValue as string).length
ts3.1版本报错问题
// 元祖类型,不能超过越界元素
let arr: [string, number] = ['1', 1]
arr[3] = '1' // error
类的高级使用
class Greeter {
static standardGreeting = 'Hello , there'
greeting: string
constructor(message?: string) {
this.greeting = message
}
greet() {
if (this.greeting) {
return 'hello' + this.greeting
} else {
return Greeting.standardGreeting
}
}
}
let greeter: Greeter
greeter = new Greeter()
console.log(greeter.greet()) // Hello, there
let greeterMaker: typeof Greeter = Greeter
greeterMaker.standardGreeting = 'Hey, there'
let greeter2: Greeter = new Greeter()
console.log(greeter.greet()) // Hey, there