1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116
| /* * X 兼容 Y: X(目标类型) = Y(源类型) */
let s: string = 'a' s = null;
// 接口兼容性 interface X { a: any; b: any; } interface Y { a: any; b: any; c: any; } let x: X = {a: 1, b: 2} let y: Y = {a: 1, b: 2, c: 3} x = y; // 函数兼容性 type Handler = (a: number, b: number) => void function hof(Handler: Handler) { return Handler }
//1)参数个数 let handler1 = (a: number) => {} hof(handler1) let handler2 = (a: number, b: number, c:number) => {} // hof(handler2)
// 可选参数和生育参数 let a = (p1: number, p2: number) => {} let b= (p1?: number, p2?: number) => {} let c = (...args: number[]) => {} a = b a = c b = c b = a c = a c = b
//2)参数类型 let handler3 = (a: string) => {} // hof(handler3)
interface Point3D { x: number; y: number; z: number; } interface Point2D { x: number; y: number; } let p3d = (point: Point3D) => {}; let p2d = (point: Point2D) => {}; p3d = p2d p2d = p3d
//3)返回值类型 let f = () => ({name: 'Alice'}); let g = () => ({name: 'Alice', location: 'Beijing'}); f = g // g = f
function overload(a: number, b: number): number; function overload(a: string, b: string): string; function overload(a: any, b: any): any {}
// 枚举兼容性 enum Fruit { Apple, Banana } enum Color { Red, Yellow } let fruit: Fruit.Apple = 3 let no: number = Fruit.Apple let color: Color.Red = Fruit.Apple
// 类兼容性 class A { constructor(p: number, q: number) {} id: number = 1 private name: string = '' } class B { static s = 1 constructor(p: number) {} id: number = 2 private name: string = '' } let aa = new A(1, 2); let bb = new B(1) // aa = bb // bb = aa class C extends A {} let cc = new C(1, 2) aa = cc cc = aa
// 泛型兼容性 interface Empty<T> { value: T } // let obj1: Empty<number> = {}; // let obj2: Empty<string> = {}; // obj1 = obj2
let log1 = <T>(x: T): T => { console.log('x') return x } let log2 = <U>(y: U): U => { console.log('y') return y } log1 = log2
|