V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
V2EX 提问指南
tuihou123321
V2EX  ›  问与答

typescript 中 interface 和泛型描述一个参数的区别

  •  
  •   tuihou123321 · 2021-05-18 20:30:05 +08:00 · 915 次点击
    这是一个创建于 1075 天前的主题,其中的信息可能已经有所发展或是发生改变。

    下面有两个函数,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 });

    3 条回复    2021-05-19 10:24:39 +08:00
    EridanusSora
        1
    EridanusSora  
       2021-05-18 23:48:28 +08:00 via Android
    这个就是标准的用泛型的场景呀
    jguo
        2
    jguo  
       2021-05-19 08:42:56 +08:00
    你似乎没理解什么是 structural typing,interface Source {}等于啥也没限制
    lbyo
        3
    lbyo  
       2021-05-19 10:24:39 +08:00
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   5427 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 26ms · UTC 07:46 · PVG 15:46 · LAX 00:46 · JFK 03:46
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.