在TS中有非常怪异的类型兼容的问题 : 如下
|
1
2
3
4
5
6
7
8
9
10
11
12
13
|
interface LengthWish{ length : number;
}class A{ length : number;
constructor(){
this.length = 2;
}
}//定义一个LengthWish类型的变量let _l : LengthWish = new A();
console.log(`length value is : ${ _l.length }`); |
在C#/Java等高级语言语言中, 可以这这么理解 : A 尚未继承 LengthWish , 所以这个会报错 .
看到结果是不是相当差异,TS这货在这点上完全不按OOP的套路出牌啊.
原理是 , 接口LengthWish中有成员字段length , 而类A中正好也有一个length字段并且类型(number)与接口一致,所以 ... 额
继续扩展 , 如下:
|
1
2
3
4
5
6
7
8
|
interface LengthWish{ length : number;
}//定义一个LengthWish类型的变量let _l : LengthWish = null;
let _c = { length : 5 , count : 10 };_l = _c;console.log(`length value is : ${ _l.length }`); |
结果如下:
不过count字段也跑进_l变量里面了:
既然count存在于_l中,我们就可以把它打印出来.其实是可以打印出来的 , 测试代码如下:
编译和结果:
很显然 , 虽然_l里面有count字段 , 但是他属于LengthWish类型,没有count字段,这就是兼容坑爹之处.
函数:
编译也会报错:
E:\WebS\MyFirst\com>tsc greeter.ts
greeter.ts(5,1): error TS2322: Type '(x: number, y: number) => number' is not assignable to type '(x: number) => number'.
但是:
可以这么理解加了Function对比参数 , 没加Function按Object理解 (注 无论加不加Function 他们都是Function类型的 , 可以断点查看)
类:
只有实例成员会被比较
正解如下
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
|
class A{ length : number;
constructor( length : number ){
this.length = length;
}
}class B{ length : number;
constructor( length : number , c : string ){
this.length = length;
}
}let a : A = new A(2);
let b : B = new B(3,'cc');
b = a;a = b; |
①注意成语一定要是一样的访问修饰符: 如下就会编译报错
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
|
class A{ private length : number;
constructor( length : number ){
this.length = length;
}
}class B{ length : number;
constructor( length : number , c : string ){
this.length = length;
}
}let a : A = new A(2);
let b : B = new B(3,'cc');
b = a;a = b; |
编译结果如下(private 和 public length的访问修饰符):
②注意成员名称要一样,一下会报错:
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
|
class A{ _length : number;
constructor( length : number ){
this._length = length;
}
}class B{ length : number;
constructor( length : number , c : string ){
this.length = length;
}
}let a : A = new A(2);
let b : B = new B(3,'cc');
b = a;a = b; |
编译结果(_length 和 length):
泛型兼容:
|
1
2
3
4
5
6
7
|
interface LengthWish<T>{}let x : LengthWish<number>;let y : LengthWish<string>;x = y;y = x; |
编译成功 , 可以理解为T可表任何类型.
总之不建议瞎搞兼容 , 还是按照OOP的思想来编写代码