// 错误示例
function f13(name : string, age : string | number) {
if (age.length) { //报错
console.log(age.length) //报错
} else {
console.log(age.toString)
}
}
f13('ljy', 21)
//Property 'length' does not exist on type 'string |number'.Property 'length' does not exist on type 'number'
// 使用类型断言示例
function f14(name : string, age : string | number) {
if ((<string>age).length) {//断言
console.log((<string>age).length)//断言
} else {
console.log(age.toString)
}
}
f14('ljy', 21)
function toBoolean(something: string | number): boolean {
return <boolean>something;
}
// Type 'string | number' cannot be converted to type 'boolean'