1.类兼容性
class Person {
public name: string = ' dwa dw' ;
public static age: number ;
public sex: string = 'ccc' ;
constructor ( name: string , age: number ) { }
}
class Animal {
public name: string = ' dwa dw' ;
constructor ( name: string ) { }
}
let p: Person;
let a: Animal;
p = a;
a = p;
class Person1 {
protected name: string = 'xiaotian' ;
}
class Animal1 {
protected name: string = 'xiaotian' ;
}
let proP1: Person1;
let A1 : Animal1;
proP1 = A1 ;
A1 = proP1;
2.接口泛型兼容性
interface TestInterface < T > {
}
let t1: TestInterface< number > ;
let t2: TestInterface< string > ;
t1 = t2;
t2 = t1;
3.交叉类型与联合类型
let mergeFn = < T , U > ( arg1: T , age2: U ) : ( T & U ) => {
let res = { } as ( T & U ) ;
res = Object. assign ( arg1, age2) ;
return res;
}
let res = mergeFn ( { name: 'xiaotian' } , { age: 22 } ) ;
console . log ( res) ;
let va1: ( number | boolean ) ;
va1 = 2123 ;
va1 = true ;
4.类型保护
let getRandom = ( ) : ( string | number ) => {
let num = Math. random ( ) ;
return ( num >= 0.5 ) ? 'abc' : 1.667
}
let res = getRandom ( ) ;
console . log ( res) ;
if ( ( res as string ) . length) {
console . log ( ( res as string ) . length) ;
} else {
console . log ( ( res as number ) . toFixed ( 2 ) ) ;
}
function isString ( value: ( number | string ) ) : value is string {
return typeof value === 'string' ;
}
if ( isString ( res) ) {
console . log ( res. length) ;
} else {
console . log ( res. toFixed ( 2 ) ) ;
}
if ( typeof res === 'string' ) {
console . log ( res. length) ;
} else {
console . log ( res. toFixed ( 2 ) ) ;
}
class Person {
name: string = 'dwad' ;
}
class Student {
age: number = 18 ;
}
let getRandomObject = ( ) : ( Person | Student) => {
let num = Math. random ( ) ;
return num >= 0.5 ? new Person ( ) : new Student ( ) ;
}
let obj = getRandomObject ( ) ;
console . log ( obj, 'obj' ) ;
if ( obj instanceof Person ) {
console . log ( obj. name) ;
} else {
console . log ( obj. age) ;
}
5.null和undefined
let val1: null ;
let val2: undefined;
let value3: number ;
let value4: ( number | null | undefined) ;
value4 = null ;
class Person {
name? : string
}
function say ( age? : number ) {
console . log ( age) ;
}
say ( ) ;
6.去除null和undefined
function getLength ( values: ( string | null | undefined) ) {
return ( ) => {
return values! . length;
}
}
getLength ( null ) ( ) ;
7.类型别名
type MyString = string ;
let value: MyString;
value = 'dwadw' ;
value = 21321 ;
value = true ;
type MyType< T > = { x: T , y: T } ;
let value1: MyType< number > ;
value1 = { x: 111 , y: 2123 } ;
value1 = { x: '21232' , y: 1234 } ;
type ChildType = {
name: string ;
children? : ChildType
}
let childrenVa1: ChildType;
childrenVa1 = {
name: 'one' ,
children: {
name: '2121' ,
children: {
name: 'dwawd'
}
}
}
type TypeObj = {
name: string
}
interface FaceObj {
name: string
}
let typeV1: TypeObj = { name: 'dwadw' } ;
let typeI1: FaceObj = { name: 'dwadwdw' } ;
typeV1 = typeI1;
typeI1 = typeV1;