1/* 2 * Copyright (c) 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 16import assert = require('assert'); 17 18function mergeObjects<T, U>(primary: T, secondary: U): T & U { 19 const merged = {} as T & U; 20 21 for (const prop in primary) { 22 merged[prop] = primary[prop] as any; 23 } 24 25 for (const prop in secondary) { 26 if (!Object.prototype.hasOwnProperty.call(merged, prop)) { 27 merged[prop] = secondary[prop] as any; 28 } 29 } 30 return merged; 31} 32 33class Human { 34 constructor(public username: string) {} 35} 36 37interface LoggingCapability { 38 writeLog(): void; 39} 40 41class TerminalLogger implements LoggingCapability { 42 writeLog(): void { 43 console.log('Jim'); 44 } 45} 46 47const user = mergeObjects(new Human('Jim'), new TerminalLogger()); 48const currentUser = user.username; 49 50assert(currentUser === 'Jim', 'success'); 51