1/* 2 * Copyright (c) 2023-2023 Huawei Device Co., Ltd. 3 * Licensed under the Apache License, Version 2.0 (the "License"); 4 * you may not use this file except in compliance with the License. 5 * You may obtain a copy of the License at 6 * 7 * http://www.apache.org/licenses/LICENSE-2.0 8 * 9 * Unless required by applicable law or agreed to in writing, software 10 * distributed under the License is distributed on an "AS IS" BASIS, 11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 * See the License for the specific language governing permissions and 13 * limitations under the License. 14 */ 15 16class X { 17 public foo: number 18 19 constructor() { 20 this.foo = 0 21 } 22} 23 24class Y { 25 public foo: number 26 constructor() { 27 this.foo = 0 28 } 29} 30 31let x = new X() 32let y = new Y() 33 34console.log("Assign X to Y") 35y = x 36 37console.log("Assign Y to X") 38x = y 39 40 41 42 43interface Z { 44 foo: number 45 } 46 47 // X implements interface Z, which makes relation between X and Y explicit. 48 class C implements Z { 49 public foo: number 50 51 constructor() { 52 this.foo = 0 53 } 54 } 55 56 // Y implements interface Z, which makes relation between X and Y explicit. 57 class C2 implements Z { 58 public foo: number 59 60 constructor() { 61 this.foo = 0 62 } 63 } 64 65 let x1: Z = new C() 66 let y1: Z = new C2() 67 68 console.log("Assign X to Y") 69 y1 = x1 // ok, both are of the same type 70 71 console.log("Assign Y to X") 72 x1 = y1 // ok, both are of the same type