下面有两个函数,mergeObj 函数使用 interface 定义,copyFields 使用泛型定义;使用泛型定义的可以能正常提示出错误,而 mergeObj 不行;如果要使用 interface 实现下面泛型的功能,要如何修改?
// 泛型,多个类型参数互联约束
// target 类型要包含 source 的类型
interface Source { }
interface Target extends Source { }
function mergeObj(target:Target, source:Source): Target { for (let key in source){ target[key]=(source)[key]; } return target; }
let obj={a:1, b:2}; let obj2={c:4};
console.log(mergeObj(obj, obj2)); // 没有报错提示
function copyFields<T extends U, U>(target: T, source: U): T { for (let id in source) { target[id] = (<T>source)[id]; } return target; }
let x = { a: 1, b: 2 };
copyFields(x, { c: 10 });
这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。
V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。
V2EX is a community of developers, designers and creative people.