类型断言
interface A{
teacher():void
}
interface B{
study():void
}
function fs():A|B{
return {}as A;
}
var obj=fs();
obj.teacher()//报错
(<A>obj).teacher()//正确
类型保护
function isTeacher(demo:A|B):demo is A{
return (<A>demo).teacher!==undefined
}
var obj:A={teacher(){console.log('teacher')}}
console.log(isTeacher(obj))//true
还可以使用typeof和instanceof
类型别名type
type Str=string
type param=()=>Str
function fn(param:param):Str{
return param()
}
fn(()=>{return "xx"})
type name="xx"|'YY'
function print(param:name){
console.log(param)
}
print("xx")
print('zz')//报错
索引签名
interface C{name:string;age:number,[index:string]:any}
function fn(param:C):void{
console.log(param)
}
fn({name:'xx',age:20,sex:'female'})
interface C{
[index:number]:string
}
const arr:C=['xx','pp']